es6.js 4.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. this.x = x;
  2190. this.y = y;
  2191. }
  2192. /**
  2193. * Gets a string with the Vector2 coordinates
  2194. * @returns a string with the Vector2 coordinates
  2195. */
  2196. Vector2.prototype.toString = function () {
  2197. return "{X: " + this.x + " Y:" + this.y + "}";
  2198. };
  2199. /**
  2200. * Gets class name
  2201. * @returns the string "Vector2"
  2202. */
  2203. Vector2.prototype.getClassName = function () {
  2204. return "Vector2";
  2205. };
  2206. /**
  2207. * Gets current vector hash code
  2208. * @returns the Vector2 hash code as a number
  2209. */
  2210. Vector2.prototype.getHashCode = function () {
  2211. var hash = this.x || 0;
  2212. hash = (hash * 397) ^ (this.y || 0);
  2213. return hash;
  2214. };
  2215. // Operators
  2216. /**
  2217. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2218. * @param array defines the source array
  2219. * @param index defines the offset in source array
  2220. * @returns the current Vector2
  2221. */
  2222. Vector2.prototype.toArray = function (array, index) {
  2223. if (index === void 0) { index = 0; }
  2224. array[index] = this.x;
  2225. array[index + 1] = this.y;
  2226. return this;
  2227. };
  2228. /**
  2229. * Copy the current vector to an array
  2230. * @returns a new array with 2 elements: the Vector2 coordinates.
  2231. */
  2232. Vector2.prototype.asArray = function () {
  2233. var result = new Array();
  2234. this.toArray(result, 0);
  2235. return result;
  2236. };
  2237. /**
  2238. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2239. * @param source defines the source Vector2
  2240. * @returns the current updated Vector2
  2241. */
  2242. Vector2.prototype.copyFrom = function (source) {
  2243. this.x = source.x;
  2244. this.y = source.y;
  2245. return this;
  2246. };
  2247. /**
  2248. * Sets the Vector2 coordinates with the given floats
  2249. * @param x defines the first coordinate
  2250. * @param y defines the second coordinate
  2251. * @returns the current updated Vector2
  2252. */
  2253. Vector2.prototype.copyFromFloats = function (x, y) {
  2254. this.x = x;
  2255. this.y = y;
  2256. return this;
  2257. };
  2258. /**
  2259. * Sets the Vector2 coordinates with the given floats
  2260. * @param x defines the first coordinate
  2261. * @param y defines the second coordinate
  2262. * @returns the current updated Vector2
  2263. */
  2264. Vector2.prototype.set = function (x, y) {
  2265. return this.copyFromFloats(x, y);
  2266. };
  2267. /**
  2268. * Add another vector with the current one
  2269. * @param otherVector defines the other vector
  2270. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2271. */
  2272. Vector2.prototype.add = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2277. * @param otherVector defines the other vector
  2278. * @param result defines the target vector
  2279. * @returns the unmodified current Vector2
  2280. */
  2281. Vector2.prototype.addToRef = function (otherVector, result) {
  2282. result.x = this.x + otherVector.x;
  2283. result.y = this.y + otherVector.y;
  2284. return this;
  2285. };
  2286. /**
  2287. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2288. * @param otherVector defines the other vector
  2289. * @returns the current updated Vector2
  2290. */
  2291. Vector2.prototype.addInPlace = function (otherVector) {
  2292. this.x += otherVector.x;
  2293. this.y += otherVector.y;
  2294. return this;
  2295. };
  2296. /**
  2297. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2298. * @param otherVector defines the other vector
  2299. * @returns a new Vector2
  2300. */
  2301. Vector2.prototype.addVector3 = function (otherVector) {
  2302. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2303. };
  2304. /**
  2305. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2306. * @param otherVector defines the other vector
  2307. * @returns a new Vector2
  2308. */
  2309. Vector2.prototype.subtract = function (otherVector) {
  2310. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2311. };
  2312. /**
  2313. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2314. * @param otherVector defines the other vector
  2315. * @param result defines the target vector
  2316. * @returns the unmodified current Vector2
  2317. */
  2318. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2319. result.x = this.x - otherVector.x;
  2320. result.y = this.y - otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2325. * @param otherVector defines the other vector
  2326. * @returns the current updated Vector2
  2327. */
  2328. Vector2.prototype.subtractInPlace = function (otherVector) {
  2329. this.x -= otherVector.x;
  2330. this.y -= otherVector.y;
  2331. return this;
  2332. };
  2333. /**
  2334. * Multiplies in place the current Vector2 coordinates by the given ones
  2335. * @param otherVector defines the other vector
  2336. * @returns the current updated Vector2
  2337. */
  2338. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2339. this.x *= otherVector.x;
  2340. this.y *= otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2345. * @param otherVector defines the other vector
  2346. * @returns a new Vector2
  2347. */
  2348. Vector2.prototype.multiply = function (otherVector) {
  2349. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2350. };
  2351. /**
  2352. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2353. * @param otherVector defines the other vector
  2354. * @param result defines the target vector
  2355. * @returns the unmodified current Vector2
  2356. */
  2357. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2358. result.x = this.x * otherVector.x;
  2359. result.y = this.y * otherVector.y;
  2360. return this;
  2361. };
  2362. /**
  2363. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2364. * @param x defines the first coordinate
  2365. * @param y defines the second coordinate
  2366. * @returns a new Vector2
  2367. */
  2368. Vector2.prototype.multiplyByFloats = function (x, y) {
  2369. return new Vector2(this.x * x, this.y * y);
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @returns a new Vector2
  2375. */
  2376. Vector2.prototype.divide = function (otherVector) {
  2377. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2378. };
  2379. /**
  2380. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2381. * @param otherVector defines the other vector
  2382. * @param result defines the target vector
  2383. * @returns the unmodified current Vector2
  2384. */
  2385. Vector2.prototype.divideToRef = function (otherVector, result) {
  2386. result.x = this.x / otherVector.x;
  2387. result.y = this.y / otherVector.y;
  2388. return this;
  2389. };
  2390. /**
  2391. * Divides the current Vector3 coordinates by the given ones
  2392. * @param otherVector defines the other vector
  2393. * @returns the current updated Vector2
  2394. */
  2395. Vector2.prototype.divideInPlace = function (otherVector) {
  2396. return this.divideToRef(otherVector, this);
  2397. };
  2398. /**
  2399. * Gets a new Vector2 with current Vector2 negated coordinates
  2400. * @returns a new Vector2
  2401. */
  2402. Vector2.prototype.negate = function () {
  2403. return new Vector2(-this.x, -this.y);
  2404. };
  2405. /**
  2406. * Multiply the Vector2 coordinates by scale
  2407. * @param scale defines the scaling factor
  2408. * @returns the current updated Vector2
  2409. */
  2410. Vector2.prototype.scaleInPlace = function (scale) {
  2411. this.x *= scale;
  2412. this.y *= scale;
  2413. return this;
  2414. };
  2415. /**
  2416. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2417. * @param scale defines the scaling factor
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.scale = function (scale) {
  2421. var result = new Vector2(0, 0);
  2422. this.scaleToRef(scale, result);
  2423. return result;
  2424. };
  2425. /**
  2426. * Scale the current Vector2 values by a factor to a given Vector2
  2427. * @param scale defines the scale factor
  2428. * @param result defines the Vector2 object where to store the result
  2429. * @returns the unmodified current Vector2
  2430. */
  2431. Vector2.prototype.scaleToRef = function (scale, result) {
  2432. result.x = this.x * scale;
  2433. result.y = this.y * scale;
  2434. return this;
  2435. };
  2436. /**
  2437. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2438. * @param scale defines the scale factor
  2439. * @param result defines the Vector2 object where to store the result
  2440. * @returns the unmodified current Vector2
  2441. */
  2442. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2443. result.x += this.x * scale;
  2444. result.y += this.y * scale;
  2445. return this;
  2446. };
  2447. /**
  2448. * Gets a boolean if two vectors are equals
  2449. * @param otherVector defines the other vector
  2450. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2451. */
  2452. Vector2.prototype.equals = function (otherVector) {
  2453. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2454. };
  2455. /**
  2456. * Gets a boolean if two vectors are equals (using an epsilon value)
  2457. * @param otherVector defines the other vector
  2458. * @param epsilon defines the minimal distance to consider equality
  2459. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2460. */
  2461. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2462. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2463. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2464. };
  2465. // Properties
  2466. /**
  2467. * Gets the length of the vector
  2468. * @returns the vector length (float)
  2469. */
  2470. Vector2.prototype.length = function () {
  2471. return Math.sqrt(this.x * this.x + this.y * this.y);
  2472. };
  2473. /**
  2474. * Gets the vector squared length
  2475. * @returns the vector squared length (float)
  2476. */
  2477. Vector2.prototype.lengthSquared = function () {
  2478. return (this.x * this.x + this.y * this.y);
  2479. };
  2480. // Methods
  2481. /**
  2482. * Normalize the vector
  2483. * @returns the current updated Vector2
  2484. */
  2485. Vector2.prototype.normalize = function () {
  2486. var len = this.length();
  2487. if (len === 0)
  2488. return this;
  2489. var num = 1.0 / len;
  2490. this.x *= num;
  2491. this.y *= num;
  2492. return this;
  2493. };
  2494. /**
  2495. * Gets a new Vector2 copied from the Vector2
  2496. * @returns a new Vector2
  2497. */
  2498. Vector2.prototype.clone = function () {
  2499. return new Vector2(this.x, this.y);
  2500. };
  2501. // Statics
  2502. /**
  2503. * Gets a new Vector2(0, 0)
  2504. * @returns a new Vector2
  2505. */
  2506. Vector2.Zero = function () {
  2507. return new Vector2(0, 0);
  2508. };
  2509. /**
  2510. * Gets a new Vector2(1, 1)
  2511. * @returns a new Vector2
  2512. */
  2513. Vector2.One = function () {
  2514. return new Vector2(1, 1);
  2515. };
  2516. /**
  2517. * Gets a new Vector2 set from the given index element of the given array
  2518. * @param array defines the data source
  2519. * @param offset defines the offset in the data source
  2520. * @returns a new Vector2
  2521. */
  2522. Vector2.FromArray = function (array, offset) {
  2523. if (offset === void 0) { offset = 0; }
  2524. return new Vector2(array[offset], array[offset + 1]);
  2525. };
  2526. /**
  2527. * Sets "result" from the given index element of the given array
  2528. * @param array defines the data source
  2529. * @param offset defines the offset in the data source
  2530. * @param result defines the target vector
  2531. */
  2532. Vector2.FromArrayToRef = function (array, offset, result) {
  2533. result.x = array[offset];
  2534. result.y = array[offset + 1];
  2535. };
  2536. /**
  2537. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2538. * @param value1 defines 1st point of control
  2539. * @param value2 defines 2nd point of control
  2540. * @param value3 defines 3rd point of control
  2541. * @param value4 defines 4th point of control
  2542. * @param amount defines the interpolation factor
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2546. var squared = amount * amount;
  2547. var cubed = amount * squared;
  2548. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2549. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2550. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2551. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2552. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2553. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2554. return new Vector2(x, y);
  2555. };
  2556. /**
  2557. * 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".
  2558. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2559. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2560. * @param value defines the value to clamp
  2561. * @param min defines the lower limit
  2562. * @param max defines the upper limit
  2563. * @returns a new Vector2
  2564. */
  2565. Vector2.Clamp = function (value, min, max) {
  2566. var x = value.x;
  2567. x = (x > max.x) ? max.x : x;
  2568. x = (x < min.x) ? min.x : x;
  2569. var y = value.y;
  2570. y = (y > max.y) ? max.y : y;
  2571. y = (y < min.y) ? min.y : y;
  2572. return new Vector2(x, y);
  2573. };
  2574. /**
  2575. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2576. * @param value1 defines the 1st control point
  2577. * @param tangent1 defines the outgoing tangent
  2578. * @param value2 defines the 2nd control point
  2579. * @param tangent2 defines the incoming tangent
  2580. * @param amount defines the interpolation factor
  2581. * @returns a new Vector2
  2582. */
  2583. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2584. var squared = amount * amount;
  2585. var cubed = amount * squared;
  2586. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2587. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2588. var part3 = (cubed - (2.0 * squared)) + amount;
  2589. var part4 = cubed - squared;
  2590. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2591. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2592. return new Vector2(x, y);
  2593. };
  2594. /**
  2595. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2596. * @param start defines the start vector
  2597. * @param end defines the end vector
  2598. * @param amount defines the interpolation factor
  2599. * @returns a new Vector2
  2600. */
  2601. Vector2.Lerp = function (start, end, amount) {
  2602. var x = start.x + ((end.x - start.x) * amount);
  2603. var y = start.y + ((end.y - start.y) * amount);
  2604. return new Vector2(x, y);
  2605. };
  2606. /**
  2607. * Gets the dot product of the vector "left" and the vector "right"
  2608. * @param left defines first vector
  2609. * @param right defines second vector
  2610. * @returns the dot product (float)
  2611. */
  2612. Vector2.Dot = function (left, right) {
  2613. return left.x * right.x + left.y * right.y;
  2614. };
  2615. /**
  2616. * Returns a new Vector2 equal to the normalized given vector
  2617. * @param vector defines the vector to normalize
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.Normalize = function (vector) {
  2621. var newVector = vector.clone();
  2622. newVector.normalize();
  2623. return newVector;
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2627. * @param left defines 1st vector
  2628. * @param right defines 2nd vector
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.Minimize = function (left, right) {
  2632. var x = (left.x < right.x) ? left.x : right.x;
  2633. var y = (left.y < right.y) ? left.y : right.y;
  2634. return new Vector2(x, y);
  2635. };
  2636. /**
  2637. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2638. * @param left defines 1st vector
  2639. * @param right defines 2nd vector
  2640. * @returns a new Vector2
  2641. */
  2642. Vector2.Maximize = function (left, right) {
  2643. var x = (left.x > right.x) ? left.x : right.x;
  2644. var y = (left.y > right.y) ? left.y : right.y;
  2645. return new Vector2(x, y);
  2646. };
  2647. /**
  2648. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2649. * @param vector defines the vector to transform
  2650. * @param transformation defines the matrix to apply
  2651. * @returns a new Vector2
  2652. */
  2653. Vector2.Transform = function (vector, transformation) {
  2654. var r = Vector2.Zero();
  2655. Vector2.TransformToRef(vector, transformation, r);
  2656. return r;
  2657. };
  2658. /**
  2659. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2660. * @param vector defines the vector to transform
  2661. * @param transformation defines the matrix to apply
  2662. * @param result defines the target vector
  2663. */
  2664. Vector2.TransformToRef = function (vector, transformation, result) {
  2665. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2666. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2667. result.x = x;
  2668. result.y = y;
  2669. };
  2670. /**
  2671. * Determines if a given vector is included in a triangle
  2672. * @param p defines the vector to test
  2673. * @param p0 defines 1st triangle point
  2674. * @param p1 defines 2nd triangle point
  2675. * @param p2 defines 3rd triangle point
  2676. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2677. */
  2678. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2679. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2680. var sign = a < 0 ? -1 : 1;
  2681. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2682. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2683. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2684. };
  2685. /**
  2686. * Gets the distance between the vectors "value1" and "value2"
  2687. * @param value1 defines first vector
  2688. * @param value2 defines second vector
  2689. * @returns the distance between vectors
  2690. */
  2691. Vector2.Distance = function (value1, value2) {
  2692. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2693. };
  2694. /**
  2695. * Returns the squared distance between the vectors "value1" and "value2"
  2696. * @param value1 defines first vector
  2697. * @param value2 defines second vector
  2698. * @returns the squared distance between vectors
  2699. */
  2700. Vector2.DistanceSquared = function (value1, value2) {
  2701. var x = value1.x - value2.x;
  2702. var y = value1.y - value2.y;
  2703. return (x * x) + (y * y);
  2704. };
  2705. /**
  2706. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2707. * @param value1 defines first vector
  2708. * @param value2 defines second vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Center = function (value1, value2) {
  2712. var center = value1.add(value2);
  2713. center.scaleInPlace(0.5);
  2714. return center;
  2715. };
  2716. /**
  2717. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2718. * @param p defines the middle point
  2719. * @param segA defines one point of the segment
  2720. * @param segB defines the other point of the segment
  2721. * @returns the shortest distance
  2722. */
  2723. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2724. var l2 = Vector2.DistanceSquared(segA, segB);
  2725. if (l2 === 0.0) {
  2726. return Vector2.Distance(p, segA);
  2727. }
  2728. var v = segB.subtract(segA);
  2729. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2730. var proj = segA.add(v.multiplyByFloats(t, t));
  2731. return Vector2.Distance(p, proj);
  2732. };
  2733. return Vector2;
  2734. }());
  2735. BABYLON.Vector2 = Vector2;
  2736. /**
  2737. * Classed used to store (x,y,z) vector representation
  2738. * A Vector3 is the main object used in 3D geometry
  2739. * It can represent etiher the coordinates of a point the space, either a direction
  2740. * Reminder: Babylon.js uses a left handed forward facing system
  2741. */
  2742. var Vector3 = /** @class */ (function () {
  2743. /**
  2744. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2745. * @param x defines the first coordinates (on X axis)
  2746. * @param y defines the second coordinates (on Y axis)
  2747. * @param z defines the third coordinates (on Z axis)
  2748. */
  2749. function Vector3(
  2750. /**
  2751. * Defines the first coordinates (on X axis)
  2752. */
  2753. x,
  2754. /**
  2755. * Defines the second coordinates (on Y axis)
  2756. */
  2757. y,
  2758. /**
  2759. * Defines the third coordinates (on Z axis)
  2760. */
  2761. z) {
  2762. this.x = x;
  2763. this.y = y;
  2764. this.z = z;
  2765. }
  2766. /**
  2767. * Creates a string representation of the Vector3
  2768. * @returns a string with the Vector3 coordinates.
  2769. */
  2770. Vector3.prototype.toString = function () {
  2771. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2772. };
  2773. /**
  2774. * Gets the class name
  2775. * @returns the string "Vector3"
  2776. */
  2777. Vector3.prototype.getClassName = function () {
  2778. return "Vector3";
  2779. };
  2780. /**
  2781. * Creates the Vector3 hash code
  2782. * @returns a number which tends to be unique between Vector3 instances
  2783. */
  2784. Vector3.prototype.getHashCode = function () {
  2785. var hash = this.x || 0;
  2786. hash = (hash * 397) ^ (this.y || 0);
  2787. hash = (hash * 397) ^ (this.z || 0);
  2788. return hash;
  2789. };
  2790. // Operators
  2791. /**
  2792. * Creates an array containing three elements : the coordinates of the Vector3
  2793. * @returns a new array of numbers
  2794. */
  2795. Vector3.prototype.asArray = function () {
  2796. var result = [];
  2797. this.toArray(result, 0);
  2798. return result;
  2799. };
  2800. /**
  2801. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2802. * @param array defines the destination array
  2803. * @param index defines the offset in the destination array
  2804. * @returns the current Vector3
  2805. */
  2806. Vector3.prototype.toArray = function (array, index) {
  2807. if (index === void 0) { index = 0; }
  2808. array[index] = this.x;
  2809. array[index + 1] = this.y;
  2810. array[index + 2] = this.z;
  2811. return this;
  2812. };
  2813. /**
  2814. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2815. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2816. */
  2817. Vector3.prototype.toQuaternion = function () {
  2818. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2819. };
  2820. /**
  2821. * Adds the given vector to the current Vector3
  2822. * @param otherVector defines the second operand
  2823. * @returns the current updated Vector3
  2824. */
  2825. Vector3.prototype.addInPlace = function (otherVector) {
  2826. this.x += otherVector.x;
  2827. this.y += otherVector.y;
  2828. this.z += otherVector.z;
  2829. return this;
  2830. };
  2831. /**
  2832. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2833. * @param otherVector defines the second operand
  2834. * @returns the resulting Vector3
  2835. */
  2836. Vector3.prototype.add = function (otherVector) {
  2837. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2838. };
  2839. /**
  2840. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2841. * @param otherVector defines the second operand
  2842. * @param result defines the Vector3 object where to store the result
  2843. * @returns the current Vector3
  2844. */
  2845. Vector3.prototype.addToRef = function (otherVector, result) {
  2846. result.x = this.x + otherVector.x;
  2847. result.y = this.y + otherVector.y;
  2848. result.z = this.z + otherVector.z;
  2849. return this;
  2850. };
  2851. /**
  2852. * Subtract the given vector from the current Vector3
  2853. * @param otherVector defines the second operand
  2854. * @returns the current updated Vector3
  2855. */
  2856. Vector3.prototype.subtractInPlace = function (otherVector) {
  2857. this.x -= otherVector.x;
  2858. this.y -= otherVector.y;
  2859. this.z -= otherVector.z;
  2860. return this;
  2861. };
  2862. /**
  2863. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2864. * @param otherVector defines the second operand
  2865. * @returns the resulting Vector3
  2866. */
  2867. Vector3.prototype.subtract = function (otherVector) {
  2868. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2869. };
  2870. /**
  2871. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2872. * @param otherVector defines the second operand
  2873. * @param result defines the Vector3 object where to store the result
  2874. * @returns the current Vector3
  2875. */
  2876. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2877. result.x = this.x - otherVector.x;
  2878. result.y = this.y - otherVector.y;
  2879. result.z = this.z - otherVector.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2884. * @param x defines the x coordinate of the operand
  2885. * @param y defines the y coordinate of the operand
  2886. * @param z defines the z coordinate of the operand
  2887. * @returns the resulting Vector3
  2888. */
  2889. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2890. return new Vector3(this.x - x, this.y - y, this.z - z);
  2891. };
  2892. /**
  2893. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2894. * @param x defines the x coordinate of the operand
  2895. * @param y defines the y coordinate of the operand
  2896. * @param z defines the z coordinate of the operand
  2897. * @param result defines the Vector3 object where to store the result
  2898. * @returns the current Vector3
  2899. */
  2900. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2901. result.x = this.x - x;
  2902. result.y = this.y - y;
  2903. result.z = this.z - z;
  2904. return this;
  2905. };
  2906. /**
  2907. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2908. * @returns a new Vector3
  2909. */
  2910. Vector3.prototype.negate = function () {
  2911. return new Vector3(-this.x, -this.y, -this.z);
  2912. };
  2913. /**
  2914. * Multiplies the Vector3 coordinates by the float "scale"
  2915. * @param scale defines the multiplier factor
  2916. * @returns the current updated Vector3
  2917. */
  2918. Vector3.prototype.scaleInPlace = function (scale) {
  2919. this.x *= scale;
  2920. this.y *= scale;
  2921. this.z *= scale;
  2922. return this;
  2923. };
  2924. /**
  2925. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2926. * @param scale defines the multiplier factor
  2927. * @returns a new Vector3
  2928. */
  2929. Vector3.prototype.scale = function (scale) {
  2930. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2931. };
  2932. /**
  2933. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2934. * @param scale defines the multiplier factor
  2935. * @param result defines the Vector3 object where to store the result
  2936. * @returns the current Vector3
  2937. */
  2938. Vector3.prototype.scaleToRef = function (scale, result) {
  2939. result.x = this.x * scale;
  2940. result.y = this.y * scale;
  2941. result.z = this.z * scale;
  2942. return this;
  2943. };
  2944. /**
  2945. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2946. * @param scale defines the scale factor
  2947. * @param result defines the Vector3 object where to store the result
  2948. * @returns the unmodified current Vector3
  2949. */
  2950. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2951. result.x += this.x * scale;
  2952. result.y += this.y * scale;
  2953. result.z += this.z * scale;
  2954. return this;
  2955. };
  2956. /**
  2957. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2958. * @param otherVector defines the second operand
  2959. * @returns true if both vectors are equals
  2960. */
  2961. Vector3.prototype.equals = function (otherVector) {
  2962. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2963. };
  2964. /**
  2965. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2966. * @param otherVector defines the second operand
  2967. * @param epsilon defines the minimal distance to define values as equals
  2968. * @returns true if both vectors are distant less than epsilon
  2969. */
  2970. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2971. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2972. 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);
  2973. };
  2974. /**
  2975. * Returns true if the current Vector3 coordinates equals the given floats
  2976. * @param x defines the x coordinate of the operand
  2977. * @param y defines the y coordinate of the operand
  2978. * @param z defines the z coordinate of the operand
  2979. * @returns true if both vectors are equals
  2980. */
  2981. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2982. return this.x === x && this.y === y && this.z === z;
  2983. };
  2984. /**
  2985. * Multiplies the current Vector3 coordinates by the given ones
  2986. * @param otherVector defines the second operand
  2987. * @returns the current updated Vector3
  2988. */
  2989. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2990. this.x *= otherVector.x;
  2991. this.y *= otherVector.y;
  2992. this.z *= otherVector.z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2997. * @param otherVector defines the second operand
  2998. * @returns the new Vector3
  2999. */
  3000. Vector3.prototype.multiply = function (otherVector) {
  3001. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3002. };
  3003. /**
  3004. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3005. * @param otherVector defines the second operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3010. result.x = this.x * otherVector.x;
  3011. result.y = this.y * otherVector.y;
  3012. result.z = this.z * otherVector.z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3017. * @param x defines the x coordinate of the operand
  3018. * @param y defines the y coordinate of the operand
  3019. * @param z defines the z coordinate of the operand
  3020. * @returns the new Vector3
  3021. */
  3022. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3023. return new Vector3(this.x * x, this.y * y, this.z * z);
  3024. };
  3025. /**
  3026. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3027. * @param otherVector defines the second operand
  3028. * @returns the new Vector3
  3029. */
  3030. Vector3.prototype.divide = function (otherVector) {
  3031. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3032. };
  3033. /**
  3034. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3035. * @param otherVector defines the second operand
  3036. * @param result defines the Vector3 object where to store the result
  3037. * @returns the current Vector3
  3038. */
  3039. Vector3.prototype.divideToRef = function (otherVector, result) {
  3040. result.x = this.x / otherVector.x;
  3041. result.y = this.y / otherVector.y;
  3042. result.z = this.z / otherVector.z;
  3043. return this;
  3044. };
  3045. /**
  3046. * Divides the current Vector3 coordinates by the given ones.
  3047. * @param otherVector defines the second operand
  3048. * @returns the current updated Vector3
  3049. */
  3050. Vector3.prototype.divideInPlace = function (otherVector) {
  3051. return this.divideToRef(otherVector, this);
  3052. };
  3053. /**
  3054. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3055. * @param other defines the second operand
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.minimizeInPlace = function (other) {
  3059. if (other.x < this.x)
  3060. this.x = other.x;
  3061. if (other.y < this.y)
  3062. this.y = other.y;
  3063. if (other.z < this.z)
  3064. this.z = other.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3069. * @param other defines the second operand
  3070. * @returns the current updated Vector3
  3071. */
  3072. Vector3.prototype.maximizeInPlace = function (other) {
  3073. if (other.x > this.x)
  3074. this.x = other.x;
  3075. if (other.y > this.y)
  3076. this.y = other.y;
  3077. if (other.z > this.z)
  3078. this.z = other.z;
  3079. return this;
  3080. };
  3081. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3082. /**
  3083. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3084. */
  3085. get: function () {
  3086. var absX = Math.abs(this.x);
  3087. var absY = Math.abs(this.y);
  3088. if (absX !== absY) {
  3089. return true;
  3090. }
  3091. var absZ = Math.abs(this.z);
  3092. if (absX !== absZ) {
  3093. return true;
  3094. }
  3095. if (absY !== absZ) {
  3096. return true;
  3097. }
  3098. return false;
  3099. },
  3100. enumerable: true,
  3101. configurable: true
  3102. });
  3103. // Properties
  3104. /**
  3105. * Gets the length of the Vector3
  3106. * @returns the length of the Vecto3
  3107. */
  3108. Vector3.prototype.length = function () {
  3109. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3110. };
  3111. /**
  3112. * Gets the squared length of the Vector3
  3113. * @returns squared length of the Vector3
  3114. */
  3115. Vector3.prototype.lengthSquared = function () {
  3116. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3117. };
  3118. /**
  3119. * Normalize the current Vector3.
  3120. * Please note that this is an in place operation.
  3121. * @returns the current updated Vector3
  3122. */
  3123. Vector3.prototype.normalize = function () {
  3124. var len = this.length();
  3125. if (len === 0 || len === 1.0)
  3126. return this;
  3127. var num = 1.0 / len;
  3128. this.x *= num;
  3129. this.y *= num;
  3130. this.z *= num;
  3131. return this;
  3132. };
  3133. /**
  3134. * Normalize the current Vector3 to a new vector
  3135. * @returns the new Vector3
  3136. */
  3137. Vector3.prototype.normalizeToNew = function () {
  3138. var normalized = new Vector3(0, 0, 0);
  3139. this.normalizeToRef(normalized);
  3140. return normalized;
  3141. };
  3142. /**
  3143. * Normalize the current Vector3 to the reference
  3144. * @param reference define the Vector3 to update
  3145. * @returns the updated Vector3
  3146. */
  3147. Vector3.prototype.normalizeToRef = function (reference) {
  3148. var len = this.length();
  3149. if (len === 0 || len === 1.0) {
  3150. reference.set(this.x, this.y, this.z);
  3151. return reference;
  3152. }
  3153. var scale = 1.0 / len;
  3154. this.scaleToRef(scale, reference);
  3155. return reference;
  3156. };
  3157. /**
  3158. * Creates a new Vector3 copied from the current Vector3
  3159. * @returns the new Vector3
  3160. */
  3161. Vector3.prototype.clone = function () {
  3162. return new Vector3(this.x, this.y, this.z);
  3163. };
  3164. /**
  3165. * Copies the given vector coordinates to the current Vector3 ones
  3166. * @param source defines the source Vector3
  3167. * @returns the current updated Vector3
  3168. */
  3169. Vector3.prototype.copyFrom = function (source) {
  3170. this.x = source.x;
  3171. this.y = source.y;
  3172. this.z = source.z;
  3173. return this;
  3174. };
  3175. /**
  3176. * Copies the given floats to the current Vector3 coordinates
  3177. * @param x defines the x coordinate of the operand
  3178. * @param y defines the y coordinate of the operand
  3179. * @param z defines the z coordinate of the operand
  3180. * @returns the current updated Vector3
  3181. */
  3182. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3183. this.x = x;
  3184. this.y = y;
  3185. this.z = z;
  3186. return this;
  3187. };
  3188. /**
  3189. * Copies the given floats to the current Vector3 coordinates
  3190. * @param x defines the x coordinate of the operand
  3191. * @param y defines the y coordinate of the operand
  3192. * @param z defines the z coordinate of the operand
  3193. * @returns the current updated Vector3
  3194. */
  3195. Vector3.prototype.set = function (x, y, z) {
  3196. return this.copyFromFloats(x, y, z);
  3197. };
  3198. // Statics
  3199. /**
  3200. * Get the clip factor between two vectors
  3201. * @param vector0 defines the first operand
  3202. * @param vector1 defines the second operand
  3203. * @param axis defines the axis to use
  3204. * @param size defines the size along the axis
  3205. * @returns the clip factor
  3206. */
  3207. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3208. var d0 = Vector3.Dot(vector0, axis) - size;
  3209. var d1 = Vector3.Dot(vector1, axis) - size;
  3210. var s = d0 / (d0 - d1);
  3211. return s;
  3212. };
  3213. /**
  3214. * Get angle between two vectors
  3215. * @param vector0 angle between vector0 and vector1
  3216. * @param vector1 angle between vector0 and vector1
  3217. * @param normal direction of the normal
  3218. * @return the angle between vector0 and vector1
  3219. */
  3220. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3221. var v0 = vector0.clone().normalize();
  3222. var v1 = vector1.clone().normalize();
  3223. var dot = Vector3.Dot(v0, v1);
  3224. var n = Vector3.Cross(v0, v1);
  3225. if (Vector3.Dot(n, normal) > 0) {
  3226. return Math.acos(dot);
  3227. }
  3228. return -Math.acos(dot);
  3229. };
  3230. /**
  3231. * Returns a new Vector3 set from the index "offset" of the given array
  3232. * @param array defines the source array
  3233. * @param offset defines the offset in the source array
  3234. * @returns the new Vector3
  3235. */
  3236. Vector3.FromArray = function (array, offset) {
  3237. if (!offset) {
  3238. offset = 0;
  3239. }
  3240. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3241. };
  3242. /**
  3243. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3244. * This function is deprecated. Use FromArray instead
  3245. * @param array defines the source array
  3246. * @param offset defines the offset in the source array
  3247. * @returns the new Vector3
  3248. */
  3249. Vector3.FromFloatArray = function (array, offset) {
  3250. return Vector3.FromArray(array, offset);
  3251. };
  3252. /**
  3253. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3254. * @param array defines the source array
  3255. * @param offset defines the offset in the source array
  3256. * @param result defines the Vector3 where to store the result
  3257. */
  3258. Vector3.FromArrayToRef = function (array, offset, result) {
  3259. result.x = array[offset];
  3260. result.y = array[offset + 1];
  3261. result.z = array[offset + 2];
  3262. };
  3263. /**
  3264. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3265. * This function is deprecated. Use FromArrayToRef instead.
  3266. * @param array defines the source array
  3267. * @param offset defines the offset in the source array
  3268. * @param result defines the Vector3 where to store the result
  3269. */
  3270. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3271. return Vector3.FromArrayToRef(array, offset, result);
  3272. };
  3273. /**
  3274. * Sets the given vector "result" with the given floats.
  3275. * @param x defines the x coordinate of the source
  3276. * @param y defines the y coordinate of the source
  3277. * @param z defines the z coordinate of the source
  3278. * @param result defines the Vector3 where to store the result
  3279. */
  3280. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3281. result.x = x;
  3282. result.y = y;
  3283. result.z = z;
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3287. * @returns a new empty Vector3
  3288. */
  3289. Vector3.Zero = function () {
  3290. return new Vector3(0.0, 0.0, 0.0);
  3291. };
  3292. /**
  3293. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3294. * @returns a new unit Vector3
  3295. */
  3296. Vector3.One = function () {
  3297. return new Vector3(1.0, 1.0, 1.0);
  3298. };
  3299. /**
  3300. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3301. * @returns a new up Vector3
  3302. */
  3303. Vector3.Up = function () {
  3304. return new Vector3(0.0, 1.0, 0.0);
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3308. * @returns a new forward Vector3
  3309. */
  3310. Vector3.Forward = function () {
  3311. return new Vector3(0.0, 0.0, 1.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3315. * @returns a new right Vector3
  3316. */
  3317. Vector3.Right = function () {
  3318. return new Vector3(1.0, 0.0, 0.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3322. * @returns a new left Vector3
  3323. */
  3324. Vector3.Left = function () {
  3325. return new Vector3(-1.0, 0.0, 0.0);
  3326. };
  3327. /**
  3328. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3329. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3330. * @param vector defines the Vector3 to transform
  3331. * @param transformation defines the transformation matrix
  3332. * @returns the transformed Vector3
  3333. */
  3334. Vector3.TransformCoordinates = function (vector, transformation) {
  3335. var result = Vector3.Zero();
  3336. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3337. return result;
  3338. };
  3339. /**
  3340. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @param result defines the Vector3 where to store the result
  3345. */
  3346. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3347. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3348. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3349. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3350. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3351. result.x = x / w;
  3352. result.y = y / w;
  3353. result.z = z / w;
  3354. };
  3355. /**
  3356. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3357. * This method computes tranformed coordinates only, not transformed direction vectors
  3358. * @param x define the x coordinate of the source vector
  3359. * @param y define the y coordinate of the source vector
  3360. * @param z define the z coordinate of the source vector
  3361. * @param transformation defines the transformation matrix
  3362. * @param result defines the Vector3 where to store the result
  3363. */
  3364. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3365. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3366. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3367. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3368. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3369. result.x = rx / rw;
  3370. result.y = ry / rw;
  3371. result.z = rz / rw;
  3372. };
  3373. /**
  3374. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3375. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3376. * @param vector defines the Vector3 to transform
  3377. * @param transformation defines the transformation matrix
  3378. * @returns the new Vector3
  3379. */
  3380. Vector3.TransformNormal = function (vector, transformation) {
  3381. var result = Vector3.Zero();
  3382. Vector3.TransformNormalToRef(vector, transformation, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @param result defines the Vector3 where to store the result
  3391. */
  3392. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3395. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3396. result.x = x;
  3397. result.y = y;
  3398. result.z = z;
  3399. };
  3400. /**
  3401. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3402. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3403. * @param x define the x coordinate of the source vector
  3404. * @param y define the y coordinate of the source vector
  3405. * @param z define the z coordinate of the source vector
  3406. * @param transformation defines the transformation matrix
  3407. * @param result defines the Vector3 where to store the result
  3408. */
  3409. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3410. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3411. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3412. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3413. };
  3414. /**
  3415. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3416. * @param value1 defines the first control point
  3417. * @param value2 defines the second control point
  3418. * @param value3 defines the third control point
  3419. * @param value4 defines the fourth control point
  3420. * @param amount defines the amount on the spline to use
  3421. * @returns the new Vector3
  3422. */
  3423. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3424. var squared = amount * amount;
  3425. var cubed = amount * squared;
  3426. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3427. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3428. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3429. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3430. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3431. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3432. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3433. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3434. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3435. return new Vector3(x, y, z);
  3436. };
  3437. /**
  3438. * 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"
  3439. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3440. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3441. * @param value defines the current value
  3442. * @param min defines the lower range value
  3443. * @param max defines the upper range value
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.Clamp = function (value, min, max) {
  3447. var x = value.x;
  3448. x = (x > max.x) ? max.x : x;
  3449. x = (x < min.x) ? min.x : x;
  3450. var y = value.y;
  3451. y = (y > max.y) ? max.y : y;
  3452. y = (y < min.y) ? min.y : y;
  3453. var z = value.z;
  3454. z = (z > max.z) ? max.z : z;
  3455. z = (z < min.z) ? min.z : z;
  3456. return new Vector3(x, y, z);
  3457. };
  3458. /**
  3459. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3460. * @param value1 defines the first control point
  3461. * @param tangent1 defines the first tangent vector
  3462. * @param value2 defines the second control point
  3463. * @param tangent2 defines the second tangent vector
  3464. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3465. * @returns the new Vector3
  3466. */
  3467. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3468. var squared = amount * amount;
  3469. var cubed = amount * squared;
  3470. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3471. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3472. var part3 = (cubed - (2.0 * squared)) + amount;
  3473. var part4 = cubed - squared;
  3474. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3475. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3476. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3477. return new Vector3(x, y, z);
  3478. };
  3479. /**
  3480. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3481. * @param start defines the start value
  3482. * @param end defines the end value
  3483. * @param amount max defines amount between both (between 0 and 1)
  3484. * @returns the new Vector3
  3485. */
  3486. Vector3.Lerp = function (start, end, amount) {
  3487. var result = new Vector3(0, 0, 0);
  3488. Vector3.LerpToRef(start, end, amount, result);
  3489. return result;
  3490. };
  3491. /**
  3492. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.LerpToRef = function (start, end, amount, result) {
  3499. result.x = start.x + ((end.x - start.x) * amount);
  3500. result.y = start.y + ((end.y - start.y) * amount);
  3501. result.z = start.z + ((end.z - start.z) * amount);
  3502. };
  3503. /**
  3504. * Returns the dot product (float) between the vectors "left" and "right"
  3505. * @param left defines the left operand
  3506. * @param right defines the right operand
  3507. * @returns the dot product
  3508. */
  3509. Vector3.Dot = function (left, right) {
  3510. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3511. };
  3512. /**
  3513. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3514. * The cross product is then orthogonal to both "left" and "right"
  3515. * @param left defines the left operand
  3516. * @param right defines the right operand
  3517. * @returns the cross product
  3518. */
  3519. Vector3.Cross = function (left, right) {
  3520. var result = Vector3.Zero();
  3521. Vector3.CrossToRef(left, right, result);
  3522. return result;
  3523. };
  3524. /**
  3525. * Sets the given vector "result" with the cross product of "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @param result defines the Vector3 where to store the result
  3530. */
  3531. Vector3.CrossToRef = function (left, right, result) {
  3532. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3533. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3534. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3535. result.copyFrom(MathTmp.Vector3[0]);
  3536. };
  3537. /**
  3538. * Returns a new Vector3 as the normalization of the given vector
  3539. * @param vector defines the Vector3 to normalize
  3540. * @returns the new Vector3
  3541. */
  3542. Vector3.Normalize = function (vector) {
  3543. var result = Vector3.Zero();
  3544. Vector3.NormalizeToRef(vector, result);
  3545. return result;
  3546. };
  3547. /**
  3548. * Sets the given vector "result" with the normalization of the given first vector
  3549. * @param vector defines the Vector3 to normalize
  3550. * @param result defines the Vector3 where to store the result
  3551. */
  3552. Vector3.NormalizeToRef = function (vector, result) {
  3553. result.copyFrom(vector);
  3554. result.normalize();
  3555. };
  3556. /**
  3557. * Project a Vector3 onto screen space
  3558. * @param vector defines the Vector3 to project
  3559. * @param world defines the world matrix to use
  3560. * @param transform defines the transform (view x projection) matrix to use
  3561. * @param viewport defines the screen viewport to use
  3562. * @returns the new Vector3
  3563. */
  3564. Vector3.Project = function (vector, world, transform, viewport) {
  3565. var cw = viewport.width;
  3566. var ch = viewport.height;
  3567. var cx = viewport.x;
  3568. var cy = viewport.y;
  3569. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3570. 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);
  3571. var matrix = MathTmp.Matrix[0];
  3572. world.multiplyToRef(transform, matrix);
  3573. matrix.multiplyToRef(viewportMatrix, matrix);
  3574. return Vector3.TransformCoordinates(vector, matrix);
  3575. };
  3576. /**
  3577. * Unproject from screen space to object space
  3578. * @param source defines the screen space Vector3 to use
  3579. * @param viewportWidth defines the current width of the viewport
  3580. * @param viewportHeight defines the current height of the viewport
  3581. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3582. * @param transform defines the transform (view x projection) matrix to use
  3583. * @returns the new Vector3
  3584. */
  3585. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3586. var matrix = MathTmp.Matrix[0];
  3587. world.multiplyToRef(transform, matrix);
  3588. matrix.invert();
  3589. source.x = source.x / viewportWidth * 2 - 1;
  3590. source.y = -(source.y / viewportHeight * 2 - 1);
  3591. var vector = Vector3.TransformCoordinates(source, matrix);
  3592. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3593. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3594. vector = vector.scale(1.0 / num);
  3595. }
  3596. return vector;
  3597. };
  3598. /**
  3599. * Unproject from screen space to object space
  3600. * @param source defines the screen space Vector3 to use
  3601. * @param viewportWidth defines the current width of the viewport
  3602. * @param viewportHeight defines the current height of the viewport
  3603. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3604. * @param view defines the view matrix to use
  3605. * @param projection defines the projection matrix to use
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3609. var result = Vector3.Zero();
  3610. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3611. return result;
  3612. };
  3613. /**
  3614. * Unproject from screen space to object space
  3615. * @param source defines the screen space Vector3 to use
  3616. * @param viewportWidth defines the current width of the viewport
  3617. * @param viewportHeight defines the current height of the viewport
  3618. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3619. * @param view defines the view matrix to use
  3620. * @param projection defines the projection matrix to use
  3621. * @param result defines the Vector3 where to store the result
  3622. */
  3623. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3624. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3625. };
  3626. /**
  3627. * Unproject from screen space to object space
  3628. * @param sourceX defines the screen space x coordinate to use
  3629. * @param sourceY defines the screen space y coordinate to use
  3630. * @param sourceZ defines the screen space z coordinate to use
  3631. * @param viewportWidth defines the current width of the viewport
  3632. * @param viewportHeight defines the current height of the viewport
  3633. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3634. * @param view defines the view matrix to use
  3635. * @param projection defines the projection matrix to use
  3636. * @param result defines the Vector3 where to store the result
  3637. */
  3638. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3639. var matrix = MathTmp.Matrix[0];
  3640. world.multiplyToRef(view, matrix);
  3641. matrix.multiplyToRef(projection, matrix);
  3642. matrix.invert();
  3643. var screenSource = MathTmp.Vector3[0];
  3644. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3645. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3646. screenSource.z = 2 * sourceZ - 1.0;
  3647. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3648. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3649. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3650. result.scaleInPlace(1.0 / num);
  3651. }
  3652. };
  3653. /**
  3654. * Gets the minimal coordinate values between two Vector3
  3655. * @param left defines the first operand
  3656. * @param right defines the second operand
  3657. * @returns the new Vector3
  3658. */
  3659. Vector3.Minimize = function (left, right) {
  3660. var min = left.clone();
  3661. min.minimizeInPlace(right);
  3662. return min;
  3663. };
  3664. /**
  3665. * Gets the maximal coordinate values between two Vector3
  3666. * @param left defines the first operand
  3667. * @param right defines the second operand
  3668. * @returns the new Vector3
  3669. */
  3670. Vector3.Maximize = function (left, right) {
  3671. var max = left.clone();
  3672. max.maximizeInPlace(right);
  3673. return max;
  3674. };
  3675. /**
  3676. * Returns the distance between the vectors "value1" and "value2"
  3677. * @param value1 defines the first operand
  3678. * @param value2 defines the second operand
  3679. * @returns the distance
  3680. */
  3681. Vector3.Distance = function (value1, value2) {
  3682. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3683. };
  3684. /**
  3685. * Returns the squared distance between the vectors "value1" and "value2"
  3686. * @param value1 defines the first operand
  3687. * @param value2 defines the second operand
  3688. * @returns the squared distance
  3689. */
  3690. Vector3.DistanceSquared = function (value1, value2) {
  3691. var x = value1.x - value2.x;
  3692. var y = value1.y - value2.y;
  3693. var z = value1.z - value2.z;
  3694. return (x * x) + (y * y) + (z * z);
  3695. };
  3696. /**
  3697. * Returns a new Vector3 located at the center between "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the new Vector3
  3701. */
  3702. Vector3.Center = function (value1, value2) {
  3703. var center = value1.add(value2);
  3704. center.scaleInPlace(0.5);
  3705. return center;
  3706. };
  3707. /**
  3708. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3709. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3710. * to something in order to rotate it from its local system to the given target system
  3711. * Note: axis1, axis2 and axis3 are normalized during this operation
  3712. * @param axis1 defines the first axis
  3713. * @param axis2 defines the second axis
  3714. * @param axis3 defines the third axis
  3715. * @returns a new Vector3
  3716. */
  3717. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3718. var rotation = Vector3.Zero();
  3719. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3720. return rotation;
  3721. };
  3722. /**
  3723. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @param ref defines the Vector3 where to store the result
  3728. */
  3729. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3730. var quat = MathTmp.Quaternion[0];
  3731. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3732. quat.toEulerAnglesToRef(ref);
  3733. };
  3734. return Vector3;
  3735. }());
  3736. BABYLON.Vector3 = Vector3;
  3737. //Vector4 class created for EulerAngle class conversion to Quaternion
  3738. var Vector4 = /** @class */ (function () {
  3739. /**
  3740. * Creates a Vector4 object from the given floats.
  3741. */
  3742. function Vector4(x, y, z, w) {
  3743. this.x = x;
  3744. this.y = y;
  3745. this.z = z;
  3746. this.w = w;
  3747. }
  3748. /**
  3749. * Returns the string with the Vector4 coordinates.
  3750. */
  3751. Vector4.prototype.toString = function () {
  3752. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3753. };
  3754. /**
  3755. * Returns the string "Vector4".
  3756. */
  3757. Vector4.prototype.getClassName = function () {
  3758. return "Vector4";
  3759. };
  3760. /**
  3761. * Returns the Vector4 hash code.
  3762. */
  3763. Vector4.prototype.getHashCode = function () {
  3764. var hash = this.x || 0;
  3765. hash = (hash * 397) ^ (this.y || 0);
  3766. hash = (hash * 397) ^ (this.z || 0);
  3767. hash = (hash * 397) ^ (this.w || 0);
  3768. return hash;
  3769. };
  3770. // Operators
  3771. /**
  3772. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3773. */
  3774. Vector4.prototype.asArray = function () {
  3775. var result = new Array();
  3776. this.toArray(result, 0);
  3777. return result;
  3778. };
  3779. /**
  3780. * Populates the given array from the given index with the Vector4 coordinates.
  3781. * Returns the Vector4.
  3782. */
  3783. Vector4.prototype.toArray = function (array, index) {
  3784. if (index === undefined) {
  3785. index = 0;
  3786. }
  3787. array[index] = this.x;
  3788. array[index + 1] = this.y;
  3789. array[index + 2] = this.z;
  3790. array[index + 3] = this.w;
  3791. return this;
  3792. };
  3793. /**
  3794. * Adds the given vector to the current Vector4.
  3795. * Returns the updated Vector4.
  3796. */
  3797. Vector4.prototype.addInPlace = function (otherVector) {
  3798. this.x += otherVector.x;
  3799. this.y += otherVector.y;
  3800. this.z += otherVector.z;
  3801. this.w += otherVector.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3806. */
  3807. Vector4.prototype.add = function (otherVector) {
  3808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3809. };
  3810. /**
  3811. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3812. * Returns the current Vector4.
  3813. */
  3814. Vector4.prototype.addToRef = function (otherVector, result) {
  3815. result.x = this.x + otherVector.x;
  3816. result.y = this.y + otherVector.y;
  3817. result.z = this.z + otherVector.z;
  3818. result.w = this.w + otherVector.w;
  3819. return this;
  3820. };
  3821. /**
  3822. * Subtract in place the given vector from the current Vector4.
  3823. * Returns the updated Vector4.
  3824. */
  3825. Vector4.prototype.subtractInPlace = function (otherVector) {
  3826. this.x -= otherVector.x;
  3827. this.y -= otherVector.y;
  3828. this.z -= otherVector.z;
  3829. this.w -= otherVector.w;
  3830. return this;
  3831. };
  3832. /**
  3833. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3834. */
  3835. Vector4.prototype.subtract = function (otherVector) {
  3836. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3837. };
  3838. /**
  3839. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3840. * Returns the current Vector4.
  3841. */
  3842. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3843. result.x = this.x - otherVector.x;
  3844. result.y = this.y - otherVector.y;
  3845. result.z = this.z - otherVector.z;
  3846. result.w = this.w - otherVector.w;
  3847. return this;
  3848. };
  3849. /**
  3850. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3851. */
  3852. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3853. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3854. };
  3855. /**
  3856. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3857. * Returns the current Vector4.
  3858. */
  3859. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3860. result.x = this.x - x;
  3861. result.y = this.y - y;
  3862. result.z = this.z - z;
  3863. result.w = this.w - w;
  3864. return this;
  3865. };
  3866. /**
  3867. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3868. */
  3869. Vector4.prototype.negate = function () {
  3870. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3871. };
  3872. /**
  3873. * Multiplies the current Vector4 coordinates by scale (float).
  3874. * Returns the updated Vector4.
  3875. */
  3876. Vector4.prototype.scaleInPlace = function (scale) {
  3877. this.x *= scale;
  3878. this.y *= scale;
  3879. this.z *= scale;
  3880. this.w *= scale;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3885. */
  3886. Vector4.prototype.scale = function (scale) {
  3887. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3888. };
  3889. /**
  3890. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3891. * Returns the current Vector4.
  3892. */
  3893. Vector4.prototype.scaleToRef = function (scale, result) {
  3894. result.x = this.x * scale;
  3895. result.y = this.y * scale;
  3896. result.z = this.z * scale;
  3897. result.w = this.w * scale;
  3898. return this;
  3899. };
  3900. /**
  3901. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3902. * @param scale defines the scale factor
  3903. * @param result defines the Vector4 object where to store the result
  3904. * @returns the unmodified current Vector4
  3905. */
  3906. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3907. result.x += this.x * scale;
  3908. result.y += this.y * scale;
  3909. result.z += this.z * scale;
  3910. result.w += this.w * scale;
  3911. return this;
  3912. };
  3913. /**
  3914. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3915. */
  3916. Vector4.prototype.equals = function (otherVector) {
  3917. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3918. };
  3919. /**
  3920. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3921. */
  3922. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3923. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3924. return otherVector
  3925. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3926. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3927. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3928. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3929. };
  3930. /**
  3931. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3932. */
  3933. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3934. return this.x === x && this.y === y && this.z === z && this.w === w;
  3935. };
  3936. /**
  3937. * Multiplies in place the current Vector4 by the given one.
  3938. * Returns the updated Vector4.
  3939. */
  3940. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3941. this.x *= otherVector.x;
  3942. this.y *= otherVector.y;
  3943. this.z *= otherVector.z;
  3944. this.w *= otherVector.w;
  3945. return this;
  3946. };
  3947. /**
  3948. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3949. */
  3950. Vector4.prototype.multiply = function (otherVector) {
  3951. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3952. };
  3953. /**
  3954. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3955. * Returns the current Vector4.
  3956. */
  3957. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3958. result.x = this.x * otherVector.x;
  3959. result.y = this.y * otherVector.y;
  3960. result.z = this.z * otherVector.z;
  3961. result.w = this.w * otherVector.w;
  3962. return this;
  3963. };
  3964. /**
  3965. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3966. */
  3967. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3968. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3972. */
  3973. Vector4.prototype.divide = function (otherVector) {
  3974. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3975. };
  3976. /**
  3977. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.divideToRef = function (otherVector, result) {
  3981. result.x = this.x / otherVector.x;
  3982. result.y = this.y / otherVector.y;
  3983. result.z = this.z / otherVector.z;
  3984. result.w = this.w / otherVector.w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Divides the current Vector3 coordinates by the given ones.
  3989. * @returns the updated Vector3.
  3990. */
  3991. Vector4.prototype.divideInPlace = function (otherVector) {
  3992. return this.divideToRef(otherVector, this);
  3993. };
  3994. /**
  3995. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3996. * @param other defines the second operand
  3997. * @returns the current updated Vector4
  3998. */
  3999. Vector4.prototype.minimizeInPlace = function (other) {
  4000. if (other.x < this.x)
  4001. this.x = other.x;
  4002. if (other.y < this.y)
  4003. this.y = other.y;
  4004. if (other.z < this.z)
  4005. this.z = other.z;
  4006. if (other.w < this.w)
  4007. this.w = other.w;
  4008. return this;
  4009. };
  4010. /**
  4011. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4012. * @param other defines the second operand
  4013. * @returns the current updated Vector4
  4014. */
  4015. Vector4.prototype.maximizeInPlace = function (other) {
  4016. if (other.x > this.x)
  4017. this.x = other.x;
  4018. if (other.y > this.y)
  4019. this.y = other.y;
  4020. if (other.z > this.z)
  4021. this.z = other.z;
  4022. if (other.w > this.w)
  4023. this.w = other.w;
  4024. return this;
  4025. };
  4026. // Properties
  4027. /**
  4028. * Returns the Vector4 length (float).
  4029. */
  4030. Vector4.prototype.length = function () {
  4031. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4032. };
  4033. /**
  4034. * Returns the Vector4 squared length (float).
  4035. */
  4036. Vector4.prototype.lengthSquared = function () {
  4037. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4038. };
  4039. // Methods
  4040. /**
  4041. * Normalizes in place the Vector4.
  4042. * Returns the updated Vector4.
  4043. */
  4044. Vector4.prototype.normalize = function () {
  4045. var len = this.length();
  4046. if (len === 0)
  4047. return this;
  4048. var num = 1.0 / len;
  4049. this.x *= num;
  4050. this.y *= num;
  4051. this.z *= num;
  4052. this.w *= num;
  4053. return this;
  4054. };
  4055. /**
  4056. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4057. */
  4058. Vector4.prototype.toVector3 = function () {
  4059. return new Vector3(this.x, this.y, this.z);
  4060. };
  4061. /**
  4062. * Returns a new Vector4 copied from the current one.
  4063. */
  4064. Vector4.prototype.clone = function () {
  4065. return new Vector4(this.x, this.y, this.z, this.w);
  4066. };
  4067. /**
  4068. * Updates the current Vector4 with the given one coordinates.
  4069. * Returns the updated Vector4.
  4070. */
  4071. Vector4.prototype.copyFrom = function (source) {
  4072. this.x = source.x;
  4073. this.y = source.y;
  4074. this.z = source.z;
  4075. this.w = source.w;
  4076. return this;
  4077. };
  4078. /**
  4079. * Updates the current Vector4 coordinates with the given floats.
  4080. * Returns the updated Vector4.
  4081. */
  4082. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4083. this.x = x;
  4084. this.y = y;
  4085. this.z = z;
  4086. this.w = w;
  4087. return this;
  4088. };
  4089. /**
  4090. * Updates the current Vector4 coordinates with the given floats.
  4091. * Returns the updated Vector4.
  4092. */
  4093. Vector4.prototype.set = function (x, y, z, w) {
  4094. return this.copyFromFloats(x, y, z, w);
  4095. };
  4096. // Statics
  4097. /**
  4098. * Returns a new Vector4 set from the starting index of the given array.
  4099. */
  4100. Vector4.FromArray = function (array, offset) {
  4101. if (!offset) {
  4102. offset = 0;
  4103. }
  4104. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4105. };
  4106. /**
  4107. * Updates the given vector "result" from the starting index of the given array.
  4108. */
  4109. Vector4.FromArrayToRef = function (array, offset, result) {
  4110. result.x = array[offset];
  4111. result.y = array[offset + 1];
  4112. result.z = array[offset + 2];
  4113. result.w = array[offset + 3];
  4114. };
  4115. /**
  4116. * Updates the given vector "result" from the starting index of the given Float32Array.
  4117. */
  4118. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4119. Vector4.FromArrayToRef(array, offset, result);
  4120. };
  4121. /**
  4122. * Updates the given vector "result" coordinates from the given floats.
  4123. */
  4124. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4125. result.x = x;
  4126. result.y = y;
  4127. result.z = z;
  4128. result.w = w;
  4129. };
  4130. /**
  4131. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4132. */
  4133. Vector4.Zero = function () {
  4134. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4135. };
  4136. /**
  4137. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4138. */
  4139. Vector4.One = function () {
  4140. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4141. };
  4142. /**
  4143. * Returns a new normalized Vector4 from the given one.
  4144. */
  4145. Vector4.Normalize = function (vector) {
  4146. var result = Vector4.Zero();
  4147. Vector4.NormalizeToRef(vector, result);
  4148. return result;
  4149. };
  4150. /**
  4151. * Updates the given vector "result" from the normalization of the given one.
  4152. */
  4153. Vector4.NormalizeToRef = function (vector, result) {
  4154. result.copyFrom(vector);
  4155. result.normalize();
  4156. };
  4157. Vector4.Minimize = function (left, right) {
  4158. var min = left.clone();
  4159. min.minimizeInPlace(right);
  4160. return min;
  4161. };
  4162. Vector4.Maximize = function (left, right) {
  4163. var max = left.clone();
  4164. max.maximizeInPlace(right);
  4165. return max;
  4166. };
  4167. /**
  4168. * Returns the distance (float) between the vectors "value1" and "value2".
  4169. */
  4170. Vector4.Distance = function (value1, value2) {
  4171. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4172. };
  4173. /**
  4174. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4175. */
  4176. Vector4.DistanceSquared = function (value1, value2) {
  4177. var x = value1.x - value2.x;
  4178. var y = value1.y - value2.y;
  4179. var z = value1.z - value2.z;
  4180. var w = value1.w - value2.w;
  4181. return (x * x) + (y * y) + (z * z) + (w * w);
  4182. };
  4183. /**
  4184. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4185. */
  4186. Vector4.Center = function (value1, value2) {
  4187. var center = value1.add(value2);
  4188. center.scaleInPlace(0.5);
  4189. return center;
  4190. };
  4191. /**
  4192. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4193. * This methods computes transformed normalized direction vectors only.
  4194. */
  4195. Vector4.TransformNormal = function (vector, transformation) {
  4196. var result = Vector4.Zero();
  4197. Vector4.TransformNormalToRef(vector, transformation, result);
  4198. return result;
  4199. };
  4200. /**
  4201. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4202. * This methods computes transformed normalized direction vectors only.
  4203. */
  4204. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4205. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4206. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4207. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4208. result.x = x;
  4209. result.y = y;
  4210. result.z = z;
  4211. result.w = vector.w;
  4212. };
  4213. /**
  4214. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4215. * This methods computes transformed normalized direction vectors only.
  4216. */
  4217. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4218. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4219. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4220. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4221. result.w = w;
  4222. };
  4223. return Vector4;
  4224. }());
  4225. BABYLON.Vector4 = Vector4;
  4226. var Size = /** @class */ (function () {
  4227. /**
  4228. * Creates a Size object from the given width and height (floats).
  4229. */
  4230. function Size(width, height) {
  4231. this.width = width;
  4232. this.height = height;
  4233. }
  4234. // Returns a string with the Size width and height.
  4235. Size.prototype.toString = function () {
  4236. return "{W: " + this.width + ", H: " + this.height + "}";
  4237. };
  4238. /**
  4239. * Returns the string "Size"
  4240. */
  4241. Size.prototype.getClassName = function () {
  4242. return "Size";
  4243. };
  4244. /**
  4245. * Returns the Size hash code.
  4246. */
  4247. Size.prototype.getHashCode = function () {
  4248. var hash = this.width || 0;
  4249. hash = (hash * 397) ^ (this.height || 0);
  4250. return hash;
  4251. };
  4252. /**
  4253. * Updates the current size from the given one.
  4254. * Returns the updated Size.
  4255. */
  4256. Size.prototype.copyFrom = function (src) {
  4257. this.width = src.width;
  4258. this.height = src.height;
  4259. };
  4260. /**
  4261. * Updates in place the current Size from the given floats.
  4262. * Returns the updated Size.
  4263. */
  4264. Size.prototype.copyFromFloats = function (width, height) {
  4265. this.width = width;
  4266. this.height = height;
  4267. return this;
  4268. };
  4269. /**
  4270. * Updates in place the current Size from the given floats.
  4271. * Returns the updated Size.
  4272. */
  4273. Size.prototype.set = function (width, height) {
  4274. return this.copyFromFloats(width, height);
  4275. };
  4276. /**
  4277. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4278. */
  4279. Size.prototype.multiplyByFloats = function (w, h) {
  4280. return new Size(this.width * w, this.height * h);
  4281. };
  4282. /**
  4283. * Returns a new Size copied from the given one.
  4284. */
  4285. Size.prototype.clone = function () {
  4286. return new Size(this.width, this.height);
  4287. };
  4288. /**
  4289. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4290. */
  4291. Size.prototype.equals = function (other) {
  4292. if (!other) {
  4293. return false;
  4294. }
  4295. return (this.width === other.width) && (this.height === other.height);
  4296. };
  4297. Object.defineProperty(Size.prototype, "surface", {
  4298. /**
  4299. * Returns the surface of the Size : width * height (float).
  4300. */
  4301. get: function () {
  4302. return this.width * this.height;
  4303. },
  4304. enumerable: true,
  4305. configurable: true
  4306. });
  4307. /**
  4308. * Returns a new Size set to (0.0, 0.0)
  4309. */
  4310. Size.Zero = function () {
  4311. return new Size(0.0, 0.0);
  4312. };
  4313. /**
  4314. * Returns a new Size set as the addition result of the current Size and the given one.
  4315. */
  4316. Size.prototype.add = function (otherSize) {
  4317. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4318. return r;
  4319. };
  4320. /**
  4321. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4322. */
  4323. Size.prototype.subtract = function (otherSize) {
  4324. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4325. return r;
  4326. };
  4327. /**
  4328. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4329. */
  4330. Size.Lerp = function (start, end, amount) {
  4331. var w = start.width + ((end.width - start.width) * amount);
  4332. var h = start.height + ((end.height - start.height) * amount);
  4333. return new Size(w, h);
  4334. };
  4335. return Size;
  4336. }());
  4337. BABYLON.Size = Size;
  4338. /**
  4339. * Class used to store quaternion data
  4340. * @see https://en.wikipedia.org/wiki/Quaternion
  4341. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4342. */
  4343. var Quaternion = /** @class */ (function () {
  4344. /**
  4345. * Creates a new Quaternion from the given floats
  4346. * @param x defines the first component (0 by default)
  4347. * @param y defines the second component (0 by default)
  4348. * @param z defines the third component (0 by default)
  4349. * @param w defines the fourth component (1.0 by default)
  4350. */
  4351. function Quaternion(
  4352. /** defines the first component (0 by default) */
  4353. x,
  4354. /** defines the second component (0 by default) */
  4355. y,
  4356. /** defines the third component (0 by default) */
  4357. z,
  4358. /** defines the fourth component (1.0 by default) */
  4359. w) {
  4360. if (x === void 0) { x = 0.0; }
  4361. if (y === void 0) { y = 0.0; }
  4362. if (z === void 0) { z = 0.0; }
  4363. if (w === void 0) { w = 1.0; }
  4364. this.x = x;
  4365. this.y = y;
  4366. this.z = z;
  4367. this.w = w;
  4368. }
  4369. /**
  4370. * Gets a string representation for the current quaternion
  4371. * @returns a string with the Quaternion coordinates
  4372. */
  4373. Quaternion.prototype.toString = function () {
  4374. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4375. };
  4376. /**
  4377. * Gets the class name of the quaternion
  4378. * @returns the string "Quaternion"
  4379. */
  4380. Quaternion.prototype.getClassName = function () {
  4381. return "Quaternion";
  4382. };
  4383. /**
  4384. * Gets a hash code for this quaternion
  4385. * @returns the quaternion hash code
  4386. */
  4387. Quaternion.prototype.getHashCode = function () {
  4388. var hash = this.x || 0;
  4389. hash = (hash * 397) ^ (this.y || 0);
  4390. hash = (hash * 397) ^ (this.z || 0);
  4391. hash = (hash * 397) ^ (this.w || 0);
  4392. return hash;
  4393. };
  4394. /**
  4395. * Copy the quaternion to an array
  4396. * @returns a new array populated with 4 elements from the quaternion coordinates
  4397. */
  4398. Quaternion.prototype.asArray = function () {
  4399. return [this.x, this.y, this.z, this.w];
  4400. };
  4401. /**
  4402. * Check if two quaternions are equals
  4403. * @param otherQuaternion defines the second operand
  4404. * @return true if the current quaternion and the given one coordinates are strictly equals
  4405. */
  4406. Quaternion.prototype.equals = function (otherQuaternion) {
  4407. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4408. };
  4409. /**
  4410. * Clone the current quaternion
  4411. * @returns a new quaternion copied from the current one
  4412. */
  4413. Quaternion.prototype.clone = function () {
  4414. return new Quaternion(this.x, this.y, this.z, this.w);
  4415. };
  4416. /**
  4417. * Copy a quaternion to the current one
  4418. * @param other defines the other quaternion
  4419. * @returns the updated current quaternion
  4420. */
  4421. Quaternion.prototype.copyFrom = function (other) {
  4422. this.x = other.x;
  4423. this.y = other.y;
  4424. this.z = other.z;
  4425. this.w = other.w;
  4426. return this;
  4427. };
  4428. /**
  4429. * Updates the current quaternion with the given float coordinates
  4430. * @param x defines the x coordinate
  4431. * @param y defines the y coordinate
  4432. * @param z defines the z coordinate
  4433. * @param w defines the w coordinate
  4434. * @returns the updated current quaternion
  4435. */
  4436. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4437. this.x = x;
  4438. this.y = y;
  4439. this.z = z;
  4440. this.w = w;
  4441. return this;
  4442. };
  4443. /**
  4444. * Updates the current quaternion from the given float coordinates
  4445. * @param x defines the x coordinate
  4446. * @param y defines the y coordinate
  4447. * @param z defines the z coordinate
  4448. * @param w defines the w coordinate
  4449. * @returns the updated current quaternion
  4450. */
  4451. Quaternion.prototype.set = function (x, y, z, w) {
  4452. return this.copyFromFloats(x, y, z, w);
  4453. };
  4454. /**
  4455. * Adds two quaternions
  4456. * @param other defines the second operand
  4457. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4458. */
  4459. Quaternion.prototype.add = function (other) {
  4460. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4461. };
  4462. /**
  4463. * Add a quaternion to the current one
  4464. * @param other defines the quaternion to add
  4465. * @returns the current quaternion
  4466. */
  4467. Quaternion.prototype.addInPlace = function (other) {
  4468. this.x += other.x;
  4469. this.y += other.y;
  4470. this.z += other.z;
  4471. this.w += other.w;
  4472. return this;
  4473. };
  4474. /**
  4475. * Subtract two quaternions
  4476. * @param other defines the second operand
  4477. * @returns a new quaternion as the subtraction result of the given one from the current one
  4478. */
  4479. Quaternion.prototype.subtract = function (other) {
  4480. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4481. };
  4482. /**
  4483. * Multiplies the current quaternion by a scale factor
  4484. * @param value defines the scale factor
  4485. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4486. */
  4487. Quaternion.prototype.scale = function (value) {
  4488. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4489. };
  4490. /**
  4491. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4492. * @param scale defines the scale factor
  4493. * @param result defines the Quaternion object where to store the result
  4494. * @returns the unmodified current quaternion
  4495. */
  4496. Quaternion.prototype.scaleToRef = function (scale, result) {
  4497. result.x = this.x * scale;
  4498. result.y = this.y * scale;
  4499. result.z = this.z * scale;
  4500. result.w = this.w * scale;
  4501. return this;
  4502. };
  4503. /**
  4504. * Multiplies in place the current quaternion by a scale factor
  4505. * @param value defines the scale factor
  4506. * @returns the current modified quaternion
  4507. */
  4508. Quaternion.prototype.scaleInPlace = function (value) {
  4509. this.x *= value;
  4510. this.y *= value;
  4511. this.z *= value;
  4512. this.w *= value;
  4513. return this;
  4514. };
  4515. /**
  4516. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4517. * @param scale defines the scale factor
  4518. * @param result defines the Quaternion object where to store the result
  4519. * @returns the unmodified current quaternion
  4520. */
  4521. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4522. result.x += this.x * scale;
  4523. result.y += this.y * scale;
  4524. result.z += this.z * scale;
  4525. result.w += this.w * scale;
  4526. return this;
  4527. };
  4528. /**
  4529. * Multiplies two quaternions
  4530. * @param q1 defines the second operand
  4531. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4532. */
  4533. Quaternion.prototype.multiply = function (q1) {
  4534. var result = new Quaternion(0, 0, 0, 1.0);
  4535. this.multiplyToRef(q1, result);
  4536. return result;
  4537. };
  4538. /**
  4539. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4540. * @param q1 defines the second operand
  4541. * @param result defines the target quaternion
  4542. * @returns the current quaternion
  4543. */
  4544. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4545. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4546. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4547. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4548. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4549. result.copyFromFloats(x, y, z, w);
  4550. return this;
  4551. };
  4552. /**
  4553. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4554. * @param q1 defines the second operand
  4555. * @returns the currentupdated quaternion
  4556. */
  4557. Quaternion.prototype.multiplyInPlace = function (q1) {
  4558. this.multiplyToRef(q1, this);
  4559. return this;
  4560. };
  4561. /**
  4562. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4563. * @param ref defines the target quaternion
  4564. * @returns the current quaternion
  4565. */
  4566. Quaternion.prototype.conjugateToRef = function (ref) {
  4567. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4568. return this;
  4569. };
  4570. /**
  4571. * Conjugates in place (1-q) the current quaternion
  4572. * @returns the current updated quaternion
  4573. */
  4574. Quaternion.prototype.conjugateInPlace = function () {
  4575. this.x *= -1;
  4576. this.y *= -1;
  4577. this.z *= -1;
  4578. return this;
  4579. };
  4580. /**
  4581. * Conjugates in place (1-q) the current quaternion
  4582. * @returns a new quaternion
  4583. */
  4584. Quaternion.prototype.conjugate = function () {
  4585. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4586. return result;
  4587. };
  4588. /**
  4589. * Gets length of current quaternion
  4590. * @returns the quaternion length (float)
  4591. */
  4592. Quaternion.prototype.length = function () {
  4593. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4594. };
  4595. /**
  4596. * Normalize in place the current quaternion
  4597. * @returns the current updated quaternion
  4598. */
  4599. Quaternion.prototype.normalize = function () {
  4600. var length = 1.0 / this.length();
  4601. this.x *= length;
  4602. this.y *= length;
  4603. this.z *= length;
  4604. this.w *= length;
  4605. return this;
  4606. };
  4607. /**
  4608. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4609. * @param order is a reserved parameter and is ignore for now
  4610. * @returns a new Vector3 containing the Euler angles
  4611. */
  4612. Quaternion.prototype.toEulerAngles = function (order) {
  4613. if (order === void 0) { order = "YZX"; }
  4614. var result = Vector3.Zero();
  4615. this.toEulerAnglesToRef(result, order);
  4616. return result;
  4617. };
  4618. /**
  4619. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4620. * @param result defines the vector which will be filled with the Euler angles
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns the current unchanged quaternion
  4623. */
  4624. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var qz = this.z;
  4627. var qx = this.x;
  4628. var qy = this.y;
  4629. var qw = this.w;
  4630. var sqw = qw * qw;
  4631. var sqz = qz * qz;
  4632. var sqx = qx * qx;
  4633. var sqy = qy * qy;
  4634. var zAxisY = qy * qz - qx * qw;
  4635. var limit = .4999999;
  4636. if (zAxisY < -limit) {
  4637. result.y = 2 * Math.atan2(qy, qw);
  4638. result.x = Math.PI / 2;
  4639. result.z = 0;
  4640. }
  4641. else if (zAxisY > limit) {
  4642. result.y = 2 * Math.atan2(qy, qw);
  4643. result.x = -Math.PI / 2;
  4644. result.z = 0;
  4645. }
  4646. else {
  4647. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4648. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4649. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4650. }
  4651. return this;
  4652. };
  4653. /**
  4654. * Updates the given rotation matrix with the current quaternion values
  4655. * @param result defines the target matrix
  4656. * @returns the current unchanged quaternion
  4657. */
  4658. Quaternion.prototype.toRotationMatrix = function (result) {
  4659. var xx = this.x * this.x;
  4660. var yy = this.y * this.y;
  4661. var zz = this.z * this.z;
  4662. var xy = this.x * this.y;
  4663. var zw = this.z * this.w;
  4664. var zx = this.z * this.x;
  4665. var yw = this.y * this.w;
  4666. var yz = this.y * this.z;
  4667. var xw = this.x * this.w;
  4668. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4669. result.m[1] = 2.0 * (xy + zw);
  4670. result.m[2] = 2.0 * (zx - yw);
  4671. result.m[3] = 0;
  4672. result.m[4] = 2.0 * (xy - zw);
  4673. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4674. result.m[6] = 2.0 * (yz + xw);
  4675. result.m[7] = 0;
  4676. result.m[8] = 2.0 * (zx + yw);
  4677. result.m[9] = 2.0 * (yz - xw);
  4678. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4679. result.m[11] = 0;
  4680. result.m[12] = 0;
  4681. result.m[13] = 0;
  4682. result.m[14] = 0;
  4683. result.m[15] = 1.0;
  4684. result._markAsUpdated();
  4685. return this;
  4686. };
  4687. /**
  4688. * Updates the current quaternion from the given rotation matrix values
  4689. * @param matrix defines the source matrix
  4690. * @returns the current updated quaternion
  4691. */
  4692. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4693. Quaternion.FromRotationMatrixToRef(matrix, this);
  4694. return this;
  4695. };
  4696. // Statics
  4697. /**
  4698. * Creates a new quaternion from a rotation matrix
  4699. * @param matrix defines the source matrix
  4700. * @returns a new quaternion created from the given rotation matrix values
  4701. */
  4702. Quaternion.FromRotationMatrix = function (matrix) {
  4703. var result = new Quaternion();
  4704. Quaternion.FromRotationMatrixToRef(matrix, result);
  4705. return result;
  4706. };
  4707. /**
  4708. * Updates the given quaternion with the given rotation matrix values
  4709. * @param matrix defines the source matrix
  4710. * @param result defines the target quaternion
  4711. */
  4712. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4713. var data = matrix.m;
  4714. var m11 = data[0], m12 = data[4], m13 = data[8];
  4715. var m21 = data[1], m22 = data[5], m23 = data[9];
  4716. var m31 = data[2], m32 = data[6], m33 = data[10];
  4717. var trace = m11 + m22 + m33;
  4718. var s;
  4719. if (trace > 0) {
  4720. s = 0.5 / Math.sqrt(trace + 1.0);
  4721. result.w = 0.25 / s;
  4722. result.x = (m32 - m23) * s;
  4723. result.y = (m13 - m31) * s;
  4724. result.z = (m21 - m12) * s;
  4725. }
  4726. else if (m11 > m22 && m11 > m33) {
  4727. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4728. result.w = (m32 - m23) / s;
  4729. result.x = 0.25 * s;
  4730. result.y = (m12 + m21) / s;
  4731. result.z = (m13 + m31) / s;
  4732. }
  4733. else if (m22 > m33) {
  4734. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4735. result.w = (m13 - m31) / s;
  4736. result.x = (m12 + m21) / s;
  4737. result.y = 0.25 * s;
  4738. result.z = (m23 + m32) / s;
  4739. }
  4740. else {
  4741. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4742. result.w = (m21 - m12) / s;
  4743. result.x = (m13 + m31) / s;
  4744. result.y = (m23 + m32) / s;
  4745. result.z = 0.25 * s;
  4746. }
  4747. };
  4748. /**
  4749. * Returns the dot product (float) between the quaternions "left" and "right"
  4750. * @param left defines the left operand
  4751. * @param right defines the right operand
  4752. * @returns the dot product
  4753. */
  4754. Quaternion.Dot = function (left, right) {
  4755. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4756. };
  4757. /**
  4758. * Checks if the two quaternions are close to each other
  4759. * @param quat0 defines the first quaternion to check
  4760. * @param quat1 defines the second quaternion to check
  4761. * @returns true if the two quaternions are close to each other
  4762. */
  4763. Quaternion.AreClose = function (quat0, quat1) {
  4764. var dot = Quaternion.Dot(quat0, quat1);
  4765. return dot >= 0;
  4766. };
  4767. /**
  4768. * Creates an empty quaternion
  4769. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4770. */
  4771. Quaternion.Zero = function () {
  4772. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4773. };
  4774. /**
  4775. * Inverse a given quaternion
  4776. * @param q defines the source quaternion
  4777. * @returns a new quaternion as the inverted current quaternion
  4778. */
  4779. Quaternion.Inverse = function (q) {
  4780. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4781. };
  4782. /**
  4783. * Creates an identity quaternion
  4784. * @returns the identity quaternion
  4785. */
  4786. Quaternion.Identity = function () {
  4787. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4788. };
  4789. /**
  4790. * Gets a boolean indicating if the given quaternion is identity
  4791. * @param quaternion defines the quaternion to check
  4792. * @returns true if the quaternion is identity
  4793. */
  4794. Quaternion.IsIdentity = function (quaternion) {
  4795. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4796. };
  4797. /**
  4798. * Creates a quaternion from a rotation around an axis
  4799. * @param axis defines the axis to use
  4800. * @param angle defines the angle to use
  4801. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4802. */
  4803. Quaternion.RotationAxis = function (axis, angle) {
  4804. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4805. };
  4806. /**
  4807. * Creates a rotation around an axis and stores it into the given quaternion
  4808. * @param axis defines the axis to use
  4809. * @param angle defines the angle to use
  4810. * @param result defines the target quaternion
  4811. * @returns the target quaternion
  4812. */
  4813. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4814. var sin = Math.sin(angle / 2);
  4815. axis.normalize();
  4816. result.w = Math.cos(angle / 2);
  4817. result.x = axis.x * sin;
  4818. result.y = axis.y * sin;
  4819. result.z = axis.z * sin;
  4820. return result;
  4821. };
  4822. /**
  4823. * Creates a new quaternion from data stored into an array
  4824. * @param array defines the data source
  4825. * @param offset defines the offset in the source array where the data starts
  4826. * @returns a new quaternion
  4827. */
  4828. Quaternion.FromArray = function (array, offset) {
  4829. if (!offset) {
  4830. offset = 0;
  4831. }
  4832. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4833. };
  4834. /**
  4835. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4836. * @param yaw defines the rotation around Y axis
  4837. * @param pitch defines the rotation around X axis
  4838. * @param roll defines the rotation around Z axis
  4839. * @returns the new quaternion
  4840. */
  4841. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4842. var q = new Quaternion();
  4843. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4844. return q;
  4845. };
  4846. /**
  4847. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @param result defines the target quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4854. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4855. var halfRoll = roll * 0.5;
  4856. var halfPitch = pitch * 0.5;
  4857. var halfYaw = yaw * 0.5;
  4858. var sinRoll = Math.sin(halfRoll);
  4859. var cosRoll = Math.cos(halfRoll);
  4860. var sinPitch = Math.sin(halfPitch);
  4861. var cosPitch = Math.cos(halfPitch);
  4862. var sinYaw = Math.sin(halfYaw);
  4863. var cosYaw = Math.cos(halfYaw);
  4864. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4865. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4866. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4867. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4868. };
  4869. /**
  4870. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4871. * @param alpha defines the rotation around first axis
  4872. * @param beta defines the rotation around second axis
  4873. * @param gamma defines the rotation around third axis
  4874. * @returns the new quaternion
  4875. */
  4876. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4877. var result = new Quaternion();
  4878. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4879. return result;
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @param result defines the target quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4889. // Produces a quaternion from Euler angles in the z-x-z orientation
  4890. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4891. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4892. var halfBeta = beta * 0.5;
  4893. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4894. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4895. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4896. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4897. };
  4898. /**
  4899. * 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)
  4900. * @param axis1 defines the first axis
  4901. * @param axis2 defines the second axis
  4902. * @param axis3 defines the third axis
  4903. * @returns the new quaternion
  4904. */
  4905. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4906. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4907. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4908. return quat;
  4909. };
  4910. /**
  4911. * 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
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @param ref defines the target quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4918. var rotMat = MathTmp.Matrix[0];
  4919. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4920. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4921. };
  4922. /**
  4923. * Interpolates between two quaternions
  4924. * @param left defines first quaternion
  4925. * @param right defines second quaternion
  4926. * @param amount defines the gradient to use
  4927. * @returns the new interpolated quaternion
  4928. */
  4929. Quaternion.Slerp = function (left, right, amount) {
  4930. var result = Quaternion.Identity();
  4931. Quaternion.SlerpToRef(left, right, amount, result);
  4932. return result;
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions and stores it into a target quaternion
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @param result defines the target quaternion
  4940. */
  4941. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4942. var num2;
  4943. var num3;
  4944. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4945. var flag = false;
  4946. if (num4 < 0) {
  4947. flag = true;
  4948. num4 = -num4;
  4949. }
  4950. if (num4 > 0.999999) {
  4951. num3 = 1 - amount;
  4952. num2 = flag ? -amount : amount;
  4953. }
  4954. else {
  4955. var num5 = Math.acos(num4);
  4956. var num6 = (1.0 / Math.sin(num5));
  4957. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4958. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4959. }
  4960. result.x = (num3 * left.x) + (num2 * right.x);
  4961. result.y = (num3 * left.y) + (num2 * right.y);
  4962. result.z = (num3 * left.z) + (num2 * right.z);
  4963. result.w = (num3 * left.w) + (num2 * right.w);
  4964. };
  4965. /**
  4966. * Interpolate between two quaternions using Hermite interpolation
  4967. * @param value1 defines first quaternion
  4968. * @param tangent1 defines the incoming tangent
  4969. * @param value2 defines second quaternion
  4970. * @param tangent2 defines the outgoing tangent
  4971. * @param amount defines the target quaternion
  4972. * @returns the new interpolated quaternion
  4973. */
  4974. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4975. var squared = amount * amount;
  4976. var cubed = amount * squared;
  4977. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4978. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4979. var part3 = (cubed - (2.0 * squared)) + amount;
  4980. var part4 = cubed - squared;
  4981. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4982. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4983. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4984. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4985. return new Quaternion(x, y, z, w);
  4986. };
  4987. return Quaternion;
  4988. }());
  4989. BABYLON.Quaternion = Quaternion;
  4990. /**
  4991. * Class used to store matrix data (4x4)
  4992. */
  4993. var Matrix = /** @class */ (function () {
  4994. /**
  4995. * Creates an empty matrix (filled with zeros)
  4996. */
  4997. function Matrix() {
  4998. this._isIdentity = false;
  4999. this._isIdentityDirty = true;
  5000. /**
  5001. * Gets or sets the internal data of the matrix
  5002. */
  5003. this.m = new Float32Array(16);
  5004. this._markAsUpdated();
  5005. }
  5006. /** @hidden */
  5007. Matrix.prototype._markAsUpdated = function () {
  5008. this.updateFlag = Matrix._updateFlagSeed++;
  5009. this._isIdentityDirty = true;
  5010. };
  5011. // Properties
  5012. /**
  5013. * Check if the current matrix is indentity
  5014. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5015. * @returns true is the matrix is the identity matrix
  5016. */
  5017. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5018. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5019. if (this._isIdentityDirty) {
  5020. this._isIdentityDirty = false;
  5021. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5022. this._isIdentity = false;
  5023. }
  5024. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5025. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5026. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5027. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5028. this._isIdentity = false;
  5029. }
  5030. else {
  5031. this._isIdentity = true;
  5032. }
  5033. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. }
  5037. return this._isIdentity;
  5038. };
  5039. /**
  5040. * Gets the determinant of the matrix
  5041. * @returns the matrix determinant
  5042. */
  5043. Matrix.prototype.determinant = function () {
  5044. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5045. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5046. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5047. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5048. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5049. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5050. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5051. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5052. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5053. };
  5054. // Methods
  5055. /**
  5056. * Returns the matrix as a Float32Array
  5057. * @returns the matrix underlying array
  5058. */
  5059. Matrix.prototype.toArray = function () {
  5060. return this.m;
  5061. };
  5062. /**
  5063. * Returns the matrix as a Float32Array
  5064. * @returns the matrix underlying array.
  5065. */
  5066. Matrix.prototype.asArray = function () {
  5067. return this.toArray();
  5068. };
  5069. /**
  5070. * Inverts the current matrix in place
  5071. * @returns the current inverted matrix
  5072. */
  5073. Matrix.prototype.invert = function () {
  5074. this.invertToRef(this);
  5075. return this;
  5076. };
  5077. /**
  5078. * Sets all the matrix elements to zero
  5079. * @returns the current matrix
  5080. */
  5081. Matrix.prototype.reset = function () {
  5082. for (var index = 0; index < 16; index++) {
  5083. this.m[index] = 0.0;
  5084. }
  5085. this._markAsUpdated();
  5086. return this;
  5087. };
  5088. /**
  5089. * Adds the current matrix with a second one
  5090. * @param other defines the matrix to add
  5091. * @returns a new matrix as the addition of the current matrix and the given one
  5092. */
  5093. Matrix.prototype.add = function (other) {
  5094. var result = new Matrix();
  5095. this.addToRef(other, result);
  5096. return result;
  5097. };
  5098. /**
  5099. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5100. * @param other defines the matrix to add
  5101. * @param result defines the target matrix
  5102. * @returns the current matrix
  5103. */
  5104. Matrix.prototype.addToRef = function (other, result) {
  5105. for (var index = 0; index < 16; index++) {
  5106. result.m[index] = this.m[index] + other.m[index];
  5107. }
  5108. result._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Adds in place the given matrix to the current matrix
  5113. * @param other defines the second operand
  5114. * @returns the current updated matrix
  5115. */
  5116. Matrix.prototype.addToSelf = function (other) {
  5117. for (var index = 0; index < 16; index++) {
  5118. this.m[index] += other.m[index];
  5119. }
  5120. this._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Sets the given matrix to the current inverted Matrix
  5125. * @param other defines the target matrix
  5126. * @returns the unmodified current matrix
  5127. */
  5128. Matrix.prototype.invertToRef = function (other) {
  5129. var l1 = this.m[0];
  5130. var l2 = this.m[1];
  5131. var l3 = this.m[2];
  5132. var l4 = this.m[3];
  5133. var l5 = this.m[4];
  5134. var l6 = this.m[5];
  5135. var l7 = this.m[6];
  5136. var l8 = this.m[7];
  5137. var l9 = this.m[8];
  5138. var l10 = this.m[9];
  5139. var l11 = this.m[10];
  5140. var l12 = this.m[11];
  5141. var l13 = this.m[12];
  5142. var l14 = this.m[13];
  5143. var l15 = this.m[14];
  5144. var l16 = this.m[15];
  5145. var l17 = (l11 * l16) - (l12 * l15);
  5146. var l18 = (l10 * l16) - (l12 * l14);
  5147. var l19 = (l10 * l15) - (l11 * l14);
  5148. var l20 = (l9 * l16) - (l12 * l13);
  5149. var l21 = (l9 * l15) - (l11 * l13);
  5150. var l22 = (l9 * l14) - (l10 * l13);
  5151. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5152. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5153. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5154. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5155. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5156. var l28 = (l7 * l16) - (l8 * l15);
  5157. var l29 = (l6 * l16) - (l8 * l14);
  5158. var l30 = (l6 * l15) - (l7 * l14);
  5159. var l31 = (l5 * l16) - (l8 * l13);
  5160. var l32 = (l5 * l15) - (l7 * l13);
  5161. var l33 = (l5 * l14) - (l6 * l13);
  5162. var l34 = (l7 * l12) - (l8 * l11);
  5163. var l35 = (l6 * l12) - (l8 * l10);
  5164. var l36 = (l6 * l11) - (l7 * l10);
  5165. var l37 = (l5 * l12) - (l8 * l9);
  5166. var l38 = (l5 * l11) - (l7 * l9);
  5167. var l39 = (l5 * l10) - (l6 * l9);
  5168. other.m[0] = l23 * l27;
  5169. other.m[4] = l24 * l27;
  5170. other.m[8] = l25 * l27;
  5171. other.m[12] = l26 * l27;
  5172. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5173. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5174. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5175. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5176. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5177. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5178. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5179. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5180. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5181. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5182. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5183. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5184. other._markAsUpdated();
  5185. return this;
  5186. };
  5187. /**
  5188. * Inserts the translation vector (using 3 floats) in the current matrix
  5189. * @param x defines the 1st component of the translation
  5190. * @param y defines the 2nd component of the translation
  5191. * @param z defines the 3rd component of the translation
  5192. * @returns the current updated matrix
  5193. */
  5194. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5195. this.m[12] = x;
  5196. this.m[13] = y;
  5197. this.m[14] = z;
  5198. this._markAsUpdated();
  5199. return this;
  5200. };
  5201. /**
  5202. * Inserts the translation vector in the current matrix
  5203. * @param vector3 defines the translation to insert
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslation = function (vector3) {
  5207. this.m[12] = vector3.x;
  5208. this.m[13] = vector3.y;
  5209. this.m[14] = vector3.z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Gets the translation value of the current matrix
  5215. * @returns a new Vector3 as the extracted translation from the matrix
  5216. */
  5217. Matrix.prototype.getTranslation = function () {
  5218. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5219. };
  5220. /**
  5221. * Fill a Vector3 with the extracted translation from the matrix
  5222. * @param result defines the Vector3 where to store the translation
  5223. * @returns the current matrix
  5224. */
  5225. Matrix.prototype.getTranslationToRef = function (result) {
  5226. result.x = this.m[12];
  5227. result.y = this.m[13];
  5228. result.z = this.m[14];
  5229. return this;
  5230. };
  5231. /**
  5232. * Remove rotation and scaling part from the matrix
  5233. * @returns the updated matrix
  5234. */
  5235. Matrix.prototype.removeRotationAndScaling = function () {
  5236. this.setRowFromFloats(0, 1, 0, 0, 0);
  5237. this.setRowFromFloats(1, 0, 1, 0, 0);
  5238. this.setRowFromFloats(2, 0, 0, 1, 0);
  5239. return this;
  5240. };
  5241. /**
  5242. * Multiply two matrices
  5243. * @param other defines the second operand
  5244. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5245. */
  5246. Matrix.prototype.multiply = function (other) {
  5247. var result = new Matrix();
  5248. this.multiplyToRef(other, result);
  5249. return result;
  5250. };
  5251. /**
  5252. * Copy the current matrix from the given one
  5253. * @param other defines the source matrix
  5254. * @returns the current updated matrix
  5255. */
  5256. Matrix.prototype.copyFrom = function (other) {
  5257. for (var index = 0; index < 16; index++) {
  5258. this.m[index] = other.m[index];
  5259. }
  5260. this._markAsUpdated();
  5261. return this;
  5262. };
  5263. /**
  5264. * Populates the given array from the starting index with the current matrix values
  5265. * @param array defines the target array
  5266. * @param offset defines the offset in the target array where to start storing values
  5267. * @returns the current matrix
  5268. */
  5269. Matrix.prototype.copyToArray = function (array, offset) {
  5270. if (offset === void 0) { offset = 0; }
  5271. for (var index = 0; index < 16; index++) {
  5272. array[offset + index] = this.m[index];
  5273. }
  5274. return this;
  5275. };
  5276. /**
  5277. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5278. * @param other defines the second operand
  5279. * @param result defines the matrix where to store the multiplication
  5280. * @returns the current matrix
  5281. */
  5282. Matrix.prototype.multiplyToRef = function (other, result) {
  5283. this.multiplyToArray(other, result.m, 0);
  5284. result._markAsUpdated();
  5285. return this;
  5286. };
  5287. /**
  5288. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5289. * @param other defines the second operand
  5290. * @param result defines the array where to store the multiplication
  5291. * @param offset defines the offset in the target array where to start storing values
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5295. var tm0 = this.m[0];
  5296. var tm1 = this.m[1];
  5297. var tm2 = this.m[2];
  5298. var tm3 = this.m[3];
  5299. var tm4 = this.m[4];
  5300. var tm5 = this.m[5];
  5301. var tm6 = this.m[6];
  5302. var tm7 = this.m[7];
  5303. var tm8 = this.m[8];
  5304. var tm9 = this.m[9];
  5305. var tm10 = this.m[10];
  5306. var tm11 = this.m[11];
  5307. var tm12 = this.m[12];
  5308. var tm13 = this.m[13];
  5309. var tm14 = this.m[14];
  5310. var tm15 = this.m[15];
  5311. var om0 = other.m[0];
  5312. var om1 = other.m[1];
  5313. var om2 = other.m[2];
  5314. var om3 = other.m[3];
  5315. var om4 = other.m[4];
  5316. var om5 = other.m[5];
  5317. var om6 = other.m[6];
  5318. var om7 = other.m[7];
  5319. var om8 = other.m[8];
  5320. var om9 = other.m[9];
  5321. var om10 = other.m[10];
  5322. var om11 = other.m[11];
  5323. var om12 = other.m[12];
  5324. var om13 = other.m[13];
  5325. var om14 = other.m[14];
  5326. var om15 = other.m[15];
  5327. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5328. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5329. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5330. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5331. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5332. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5333. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5334. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5335. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5336. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5337. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5338. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5339. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5340. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5341. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5342. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5343. return this;
  5344. };
  5345. /**
  5346. * Check equality between this matrix and a second one
  5347. * @param value defines the second matrix to compare
  5348. * @returns true is the current matrix and the given one values are strictly equal
  5349. */
  5350. Matrix.prototype.equals = function (value) {
  5351. return value &&
  5352. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5353. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5354. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5355. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5356. };
  5357. /**
  5358. * Clone the current matrix
  5359. * @returns a new matrix from the current matrix
  5360. */
  5361. Matrix.prototype.clone = function () {
  5362. 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]);
  5363. };
  5364. /**
  5365. * Returns the name of the current matrix class
  5366. * @returns the string "Matrix"
  5367. */
  5368. Matrix.prototype.getClassName = function () {
  5369. return "Matrix";
  5370. };
  5371. /**
  5372. * Gets the hash code of the current matrix
  5373. * @returns the hash code
  5374. */
  5375. Matrix.prototype.getHashCode = function () {
  5376. var hash = this.m[0] || 0;
  5377. for (var i = 1; i < 16; i++) {
  5378. hash = (hash * 397) ^ (this.m[i] || 0);
  5379. }
  5380. return hash;
  5381. };
  5382. /**
  5383. * Decomposes the current Matrix into a translation, rotation and scaling components
  5384. * @param scale defines the scale vector3 given as a reference to update
  5385. * @param rotation defines the rotation quaternion given as a reference to update
  5386. * @param translation defines the translation vector3 given as a reference to update
  5387. * @returns true if operation was successful
  5388. */
  5389. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5390. if (translation) {
  5391. translation.x = this.m[12];
  5392. translation.y = this.m[13];
  5393. translation.z = this.m[14];
  5394. }
  5395. scale = scale || MathTmp.Vector3[0];
  5396. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5397. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5398. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5399. if (this.determinant() <= 0) {
  5400. scale.y *= -1;
  5401. }
  5402. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5403. if (rotation) {
  5404. rotation.x = 0;
  5405. rotation.y = 0;
  5406. rotation.z = 0;
  5407. rotation.w = 1;
  5408. }
  5409. return false;
  5410. }
  5411. if (rotation) {
  5412. 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]);
  5413. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5414. }
  5415. return true;
  5416. };
  5417. /**
  5418. * Gets specific row of the matrix
  5419. * @param index defines the number of the row to get
  5420. * @returns the index-th row of the current matrix as a new Vector4
  5421. */
  5422. Matrix.prototype.getRow = function (index) {
  5423. if (index < 0 || index > 3) {
  5424. return null;
  5425. }
  5426. var i = index * 4;
  5427. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5428. };
  5429. /**
  5430. * Sets the index-th row of the current matrix to the vector4 values
  5431. * @param index defines the number of the row to set
  5432. * @param row defines the target vector4
  5433. * @returns the updated current matrix
  5434. */
  5435. Matrix.prototype.setRow = function (index, row) {
  5436. if (index < 0 || index > 3) {
  5437. return this;
  5438. }
  5439. var i = index * 4;
  5440. this.m[i + 0] = row.x;
  5441. this.m[i + 1] = row.y;
  5442. this.m[i + 2] = row.z;
  5443. this.m[i + 3] = row.w;
  5444. this._markAsUpdated();
  5445. return this;
  5446. };
  5447. /**
  5448. * Compute the transpose of the matrix
  5449. * @returns the new transposed matrix
  5450. */
  5451. Matrix.prototype.transpose = function () {
  5452. return Matrix.Transpose(this);
  5453. };
  5454. /**
  5455. * Compute the transpose of the matrix and store it in a given matrix
  5456. * @param result defines the target matrix
  5457. * @returns the current matrix
  5458. */
  5459. Matrix.prototype.transposeToRef = function (result) {
  5460. Matrix.TransposeToRef(this, result);
  5461. return this;
  5462. };
  5463. /**
  5464. * Sets the index-th row of the current matrix with the given 4 x float values
  5465. * @param index defines the row index
  5466. * @param x defines the x component to set
  5467. * @param y defines the y component to set
  5468. * @param z defines the z component to set
  5469. * @param w defines the w component to set
  5470. * @returns the updated current matrix
  5471. */
  5472. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5473. if (index < 0 || index > 3) {
  5474. return this;
  5475. }
  5476. var i = index * 4;
  5477. this.m[i + 0] = x;
  5478. this.m[i + 1] = y;
  5479. this.m[i + 2] = z;
  5480. this.m[i + 3] = w;
  5481. this._markAsUpdated();
  5482. return this;
  5483. };
  5484. /**
  5485. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5486. * @param scale defines the scale factor
  5487. * @returns a new matrix
  5488. */
  5489. Matrix.prototype.scale = function (scale) {
  5490. var result = new Matrix();
  5491. this.scaleToRef(scale, result);
  5492. return result;
  5493. };
  5494. /**
  5495. * Scale the current matrix values by a factor to a given result matrix
  5496. * @param scale defines the scale factor
  5497. * @param result defines the matrix to store the result
  5498. * @returns the current matrix
  5499. */
  5500. Matrix.prototype.scaleToRef = function (scale, result) {
  5501. for (var index = 0; index < 16; index++) {
  5502. result.m[index] = this.m[index] * scale;
  5503. }
  5504. result._markAsUpdated();
  5505. return this;
  5506. };
  5507. /**
  5508. * Scale the current matrix values by a factor and add the result to a given matrix
  5509. * @param scale defines the scale factor
  5510. * @param result defines the Matrix to store the result
  5511. * @returns the current matrix
  5512. */
  5513. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5514. for (var index = 0; index < 16; index++) {
  5515. result.m[index] += this.m[index] * scale;
  5516. }
  5517. result._markAsUpdated();
  5518. return this;
  5519. };
  5520. /**
  5521. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5522. * @param ref matrix to store the result
  5523. */
  5524. Matrix.prototype.toNormalMatrix = function (ref) {
  5525. this.invertToRef(ref);
  5526. ref.transpose();
  5527. var m = ref.m;
  5528. 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);
  5529. };
  5530. /**
  5531. * Gets only rotation part of the current matrix
  5532. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5533. */
  5534. Matrix.prototype.getRotationMatrix = function () {
  5535. var result = Matrix.Identity();
  5536. this.getRotationMatrixToRef(result);
  5537. return result;
  5538. };
  5539. /**
  5540. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5541. * @param result defines the target matrix to store data to
  5542. * @returns the current matrix
  5543. */
  5544. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5545. var m = this.m;
  5546. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5547. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5548. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5549. if (this.determinant() <= 0) {
  5550. sy *= -1;
  5551. }
  5552. if (sx === 0 || sy === 0 || sz === 0) {
  5553. Matrix.IdentityToRef(result);
  5554. }
  5555. else {
  5556. 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);
  5557. }
  5558. return this;
  5559. };
  5560. // Statics
  5561. /**
  5562. * Creates a matrix from an array
  5563. * @param array defines the source array
  5564. * @param offset defines an offset in the source array
  5565. * @returns a new Matrix set from the starting index of the given array
  5566. */
  5567. Matrix.FromArray = function (array, offset) {
  5568. var result = new Matrix();
  5569. if (!offset) {
  5570. offset = 0;
  5571. }
  5572. Matrix.FromArrayToRef(array, offset, result);
  5573. return result;
  5574. };
  5575. /**
  5576. * Copy the content of an array into a given matrix
  5577. * @param array defines the source array
  5578. * @param offset defines an offset in the source array
  5579. * @param result defines the target matrix
  5580. */
  5581. Matrix.FromArrayToRef = function (array, offset, result) {
  5582. for (var index = 0; index < 16; index++) {
  5583. result.m[index] = array[index + offset];
  5584. }
  5585. result._markAsUpdated();
  5586. };
  5587. /**
  5588. * Stores an array into a matrix after having multiplied each component by a given factor
  5589. * @param array defines the source array
  5590. * @param offset defines the offset in the source array
  5591. * @param scale defines the scaling factor
  5592. * @param result defines the target matrix
  5593. */
  5594. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5595. for (var index = 0; index < 16; index++) {
  5596. result.m[index] = array[index + offset] * scale;
  5597. }
  5598. result._markAsUpdated();
  5599. };
  5600. /**
  5601. * Stores a list of values (16) inside a given matrix
  5602. * @param initialM11 defines 1st value of 1st row
  5603. * @param initialM12 defines 2nd value of 1st row
  5604. * @param initialM13 defines 3rd value of 1st row
  5605. * @param initialM14 defines 4th value of 1st row
  5606. * @param initialM21 defines 1st value of 2nd row
  5607. * @param initialM22 defines 2nd value of 2nd row
  5608. * @param initialM23 defines 3rd value of 2nd row
  5609. * @param initialM24 defines 4th value of 2nd row
  5610. * @param initialM31 defines 1st value of 3rd row
  5611. * @param initialM32 defines 2nd value of 3rd row
  5612. * @param initialM33 defines 3rd value of 3rd row
  5613. * @param initialM34 defines 4th value of 3rd row
  5614. * @param initialM41 defines 1st value of 4th row
  5615. * @param initialM42 defines 2nd value of 4th row
  5616. * @param initialM43 defines 3rd value of 4th row
  5617. * @param initialM44 defines 4th value of 4th row
  5618. * @param result defines the target matrix
  5619. */
  5620. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5621. result.m[0] = initialM11;
  5622. result.m[1] = initialM12;
  5623. result.m[2] = initialM13;
  5624. result.m[3] = initialM14;
  5625. result.m[4] = initialM21;
  5626. result.m[5] = initialM22;
  5627. result.m[6] = initialM23;
  5628. result.m[7] = initialM24;
  5629. result.m[8] = initialM31;
  5630. result.m[9] = initialM32;
  5631. result.m[10] = initialM33;
  5632. result.m[11] = initialM34;
  5633. result.m[12] = initialM41;
  5634. result.m[13] = initialM42;
  5635. result.m[14] = initialM43;
  5636. result.m[15] = initialM44;
  5637. result._markAsUpdated();
  5638. };
  5639. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5640. /**
  5641. * Gets an identity matrix that must not be updated
  5642. */
  5643. get: function () {
  5644. return Matrix._identityReadOnly;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. /**
  5650. * Creates new matrix from a list of values (16)
  5651. * @param initialM11 defines 1st value of 1st row
  5652. * @param initialM12 defines 2nd value of 1st row
  5653. * @param initialM13 defines 3rd value of 1st row
  5654. * @param initialM14 defines 4th value of 1st row
  5655. * @param initialM21 defines 1st value of 2nd row
  5656. * @param initialM22 defines 2nd value of 2nd row
  5657. * @param initialM23 defines 3rd value of 2nd row
  5658. * @param initialM24 defines 4th value of 2nd row
  5659. * @param initialM31 defines 1st value of 3rd row
  5660. * @param initialM32 defines 2nd value of 3rd row
  5661. * @param initialM33 defines 3rd value of 3rd row
  5662. * @param initialM34 defines 4th value of 3rd row
  5663. * @param initialM41 defines 1st value of 4th row
  5664. * @param initialM42 defines 2nd value of 4th row
  5665. * @param initialM43 defines 3rd value of 4th row
  5666. * @param initialM44 defines 4th value of 4th row
  5667. * @returns the new matrix
  5668. */
  5669. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5670. var result = new Matrix();
  5671. result.m[0] = initialM11;
  5672. result.m[1] = initialM12;
  5673. result.m[2] = initialM13;
  5674. result.m[3] = initialM14;
  5675. result.m[4] = initialM21;
  5676. result.m[5] = initialM22;
  5677. result.m[6] = initialM23;
  5678. result.m[7] = initialM24;
  5679. result.m[8] = initialM31;
  5680. result.m[9] = initialM32;
  5681. result.m[10] = initialM33;
  5682. result.m[11] = initialM34;
  5683. result.m[12] = initialM41;
  5684. result.m[13] = initialM42;
  5685. result.m[14] = initialM43;
  5686. result.m[15] = initialM44;
  5687. return result;
  5688. };
  5689. /**
  5690. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5691. * @param scale defines the scale vector3
  5692. * @param rotation defines the rotation quaternion
  5693. * @param translation defines the translation vector3
  5694. * @returns a new matrix
  5695. */
  5696. Matrix.Compose = function (scale, rotation, translation) {
  5697. var result = Matrix.Identity();
  5698. Matrix.ComposeToRef(scale, rotation, translation, result);
  5699. return result;
  5700. };
  5701. /**
  5702. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @param result defines the target matrix
  5707. */
  5708. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5709. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5710. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5711. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5712. result.setTranslation(translation);
  5713. };
  5714. /**
  5715. * Creates a new identity matrix
  5716. * @returns a new identity matrix
  5717. */
  5718. Matrix.Identity = function () {
  5719. 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);
  5720. };
  5721. /**
  5722. * Creates a new identity matrix and stores the result in a given matrix
  5723. * @param result defines the target matrix
  5724. */
  5725. Matrix.IdentityToRef = function (result) {
  5726. 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);
  5727. };
  5728. /**
  5729. * Creates a new zero matrix
  5730. * @returns a new zero matrix
  5731. */
  5732. Matrix.Zero = function () {
  5733. 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);
  5734. };
  5735. /**
  5736. * Creates a new rotation matrix for "angle" radians around the X axis
  5737. * @param angle defines the angle (in radians) to use
  5738. * @return the new matrix
  5739. */
  5740. Matrix.RotationX = function (angle) {
  5741. var result = new Matrix();
  5742. Matrix.RotationXToRef(angle, result);
  5743. return result;
  5744. };
  5745. /**
  5746. * Creates a new matrix as the invert of a given matrix
  5747. * @param source defines the source matrix
  5748. * @returns the new matrix
  5749. */
  5750. Matrix.Invert = function (source) {
  5751. var result = new Matrix();
  5752. source.invertToRef(result);
  5753. return result;
  5754. };
  5755. /**
  5756. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5757. * @param angle defines the angle (in radians) to use
  5758. * @param result defines the target matrix
  5759. */
  5760. Matrix.RotationXToRef = function (angle, result) {
  5761. var s = Math.sin(angle);
  5762. var c = Math.cos(angle);
  5763. result.m[0] = 1.0;
  5764. result.m[15] = 1.0;
  5765. result.m[5] = c;
  5766. result.m[10] = c;
  5767. result.m[9] = -s;
  5768. result.m[6] = s;
  5769. result.m[1] = 0.0;
  5770. result.m[2] = 0.0;
  5771. result.m[3] = 0.0;
  5772. result.m[4] = 0.0;
  5773. result.m[7] = 0.0;
  5774. result.m[8] = 0.0;
  5775. result.m[11] = 0.0;
  5776. result.m[12] = 0.0;
  5777. result.m[13] = 0.0;
  5778. result.m[14] = 0.0;
  5779. result._markAsUpdated();
  5780. };
  5781. /**
  5782. * Creates a new rotation matrix for "angle" radians around the Y axis
  5783. * @param angle defines the angle (in radians) to use
  5784. * @return the new matrix
  5785. */
  5786. Matrix.RotationY = function (angle) {
  5787. var result = new Matrix();
  5788. Matrix.RotationYToRef(angle, result);
  5789. return result;
  5790. };
  5791. /**
  5792. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5793. * @param angle defines the angle (in radians) to use
  5794. * @param result defines the target matrix
  5795. */
  5796. Matrix.RotationYToRef = function (angle, result) {
  5797. var s = Math.sin(angle);
  5798. var c = Math.cos(angle);
  5799. result.m[5] = 1.0;
  5800. result.m[15] = 1.0;
  5801. result.m[0] = c;
  5802. result.m[2] = -s;
  5803. result.m[8] = s;
  5804. result.m[10] = c;
  5805. result.m[1] = 0.0;
  5806. result.m[3] = 0.0;
  5807. result.m[4] = 0.0;
  5808. result.m[6] = 0.0;
  5809. result.m[7] = 0.0;
  5810. result.m[9] = 0.0;
  5811. result.m[11] = 0.0;
  5812. result.m[12] = 0.0;
  5813. result.m[13] = 0.0;
  5814. result.m[14] = 0.0;
  5815. result._markAsUpdated();
  5816. };
  5817. /**
  5818. * Creates a new rotation matrix for "angle" radians around the Z axis
  5819. * @param angle defines the angle (in radians) to use
  5820. * @return the new matrix
  5821. */
  5822. Matrix.RotationZ = function (angle) {
  5823. var result = new Matrix();
  5824. Matrix.RotationZToRef(angle, result);
  5825. return result;
  5826. };
  5827. /**
  5828. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5829. * @param angle defines the angle (in radians) to use
  5830. * @param result defines the target matrix
  5831. */
  5832. Matrix.RotationZToRef = function (angle, result) {
  5833. var s = Math.sin(angle);
  5834. var c = Math.cos(angle);
  5835. result.m[10] = 1.0;
  5836. result.m[15] = 1.0;
  5837. result.m[0] = c;
  5838. result.m[1] = s;
  5839. result.m[4] = -s;
  5840. result.m[5] = c;
  5841. result.m[2] = 0.0;
  5842. result.m[3] = 0.0;
  5843. result.m[6] = 0.0;
  5844. result.m[7] = 0.0;
  5845. result.m[8] = 0.0;
  5846. result.m[9] = 0.0;
  5847. result.m[11] = 0.0;
  5848. result.m[12] = 0.0;
  5849. result.m[13] = 0.0;
  5850. result.m[14] = 0.0;
  5851. result._markAsUpdated();
  5852. };
  5853. /**
  5854. * Creates a new rotation matrix for "angle" radians around the given axis
  5855. * @param axis defines the axis to use
  5856. * @param angle defines the angle (in radians) to use
  5857. * @return the new matrix
  5858. */
  5859. Matrix.RotationAxis = function (axis, angle) {
  5860. var result = Matrix.Zero();
  5861. Matrix.RotationAxisToRef(axis, angle, result);
  5862. return result;
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5866. * @param axis defines the axis to use
  5867. * @param angle defines the angle (in radians) to use
  5868. * @param result defines the target matrix
  5869. */
  5870. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5871. var s = Math.sin(-angle);
  5872. var c = Math.cos(-angle);
  5873. var c1 = 1 - c;
  5874. axis.normalize();
  5875. result.m[0] = (axis.x * axis.x) * c1 + c;
  5876. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5877. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5878. result.m[3] = 0.0;
  5879. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5880. result.m[5] = (axis.y * axis.y) * c1 + c;
  5881. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5882. result.m[7] = 0.0;
  5883. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5884. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5885. result.m[10] = (axis.z * axis.z) * c1 + c;
  5886. result.m[11] = 0.0;
  5887. result.m[15] = 1.0;
  5888. result._markAsUpdated();
  5889. };
  5890. /**
  5891. * Creates a rotation matrix
  5892. * @param yaw defines the yaw angle in radians (Y axis)
  5893. * @param pitch defines the pitch angle in radians (X axis)
  5894. * @param roll defines the roll angle in radians (X axis)
  5895. * @returns the new rotation matrix
  5896. */
  5897. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5898. var result = new Matrix();
  5899. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5900. return result;
  5901. };
  5902. /**
  5903. * Creates a rotation matrix and stores it in a given matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @param result defines the target matrix
  5908. */
  5909. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5910. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5911. this._tempQuaternion.toRotationMatrix(result);
  5912. };
  5913. /**
  5914. * Creates a scaling matrix
  5915. * @param x defines the scale factor on X axis
  5916. * @param y defines the scale factor on Y axis
  5917. * @param z defines the scale factor on Z axis
  5918. * @returns the new matrix
  5919. */
  5920. Matrix.Scaling = function (x, y, z) {
  5921. var result = Matrix.Zero();
  5922. Matrix.ScalingToRef(x, y, z, result);
  5923. return result;
  5924. };
  5925. /**
  5926. * Creates a scaling matrix and stores it in a given matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @param result defines the target matrix
  5931. */
  5932. Matrix.ScalingToRef = function (x, y, z, result) {
  5933. result.m[0] = x;
  5934. result.m[1] = 0.0;
  5935. result.m[2] = 0.0;
  5936. result.m[3] = 0.0;
  5937. result.m[4] = 0.0;
  5938. result.m[5] = y;
  5939. result.m[6] = 0.0;
  5940. result.m[7] = 0.0;
  5941. result.m[8] = 0.0;
  5942. result.m[9] = 0.0;
  5943. result.m[10] = z;
  5944. result.m[11] = 0.0;
  5945. result.m[12] = 0.0;
  5946. result.m[13] = 0.0;
  5947. result.m[14] = 0.0;
  5948. result.m[15] = 1.0;
  5949. result._markAsUpdated();
  5950. };
  5951. /**
  5952. * Creates a translation matrix
  5953. * @param x defines the translation on X axis
  5954. * @param y defines the translation on Y axis
  5955. * @param z defines the translationon Z axis
  5956. * @returns the new matrix
  5957. */
  5958. Matrix.Translation = function (x, y, z) {
  5959. var result = Matrix.Identity();
  5960. Matrix.TranslationToRef(x, y, z, result);
  5961. return result;
  5962. };
  5963. /**
  5964. * Creates a translation matrix and stores it in a given matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @param result defines the target matrix
  5969. */
  5970. Matrix.TranslationToRef = function (x, y, z, result) {
  5971. 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);
  5972. };
  5973. /**
  5974. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5975. * @param startValue defines the start value
  5976. * @param endValue defines the end value
  5977. * @param gradient defines the gradient factor
  5978. * @returns the new matrix
  5979. */
  5980. Matrix.Lerp = function (startValue, endValue, gradient) {
  5981. var result = Matrix.Zero();
  5982. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @param result defines the Matrix object where to store data
  5991. */
  5992. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5993. for (var index = 0; index < 16; index++) {
  5994. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5995. }
  5996. result._markAsUpdated();
  5997. };
  5998. /**
  5999. * Builds a new matrix whose values are computed by:
  6000. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6001. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6002. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6003. * @param startValue defines the first matrix
  6004. * @param endValue defines the second matrix
  6005. * @param gradient defines the gradient between the two matrices
  6006. * @returns the new matrix
  6007. */
  6008. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6009. var result = Matrix.Zero();
  6010. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6011. return result;
  6012. };
  6013. /**
  6014. * Update a matrix to values which are computed by:
  6015. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6016. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6017. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6018. * @param startValue defines the first matrix
  6019. * @param endValue defines the second matrix
  6020. * @param gradient defines the gradient between the two matrices
  6021. * @param result defines the target matrix
  6022. */
  6023. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6024. var startScale = MathTmp.Vector3[0];
  6025. var startRotation = MathTmp.Quaternion[0];
  6026. var startTranslation = MathTmp.Vector3[1];
  6027. startValue.decompose(startScale, startRotation, startTranslation);
  6028. var endScale = MathTmp.Vector3[2];
  6029. var endRotation = MathTmp.Quaternion[1];
  6030. var endTranslation = MathTmp.Vector3[3];
  6031. endValue.decompose(endScale, endRotation, endTranslation);
  6032. var resultScale = MathTmp.Vector3[4];
  6033. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6034. var resultRotation = MathTmp.Quaternion[2];
  6035. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6036. var resultTranslation = MathTmp.Vector3[5];
  6037. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6038. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6039. };
  6040. /**
  6041. * 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"
  6042. * This function works in left handed mode
  6043. * @param eye defines the final position of the entity
  6044. * @param target defines where the entity should look at
  6045. * @param up defines the up vector for the entity
  6046. * @returns the new matrix
  6047. */
  6048. Matrix.LookAtLH = function (eye, target, up) {
  6049. var result = Matrix.Zero();
  6050. Matrix.LookAtLHToRef(eye, target, up, result);
  6051. return result;
  6052. };
  6053. /**
  6054. * 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".
  6055. * This function works in left handed mode
  6056. * @param eye defines the final position of the entity
  6057. * @param target defines where the entity should look at
  6058. * @param up defines the up vector for the entity
  6059. * @param result defines the target matrix
  6060. */
  6061. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6062. // Z axis
  6063. target.subtractToRef(eye, this._zAxis);
  6064. this._zAxis.normalize();
  6065. // X axis
  6066. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6067. if (this._xAxis.lengthSquared() === 0) {
  6068. this._xAxis.x = 1.0;
  6069. }
  6070. else {
  6071. this._xAxis.normalize();
  6072. }
  6073. // Y axis
  6074. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6075. this._yAxis.normalize();
  6076. // Eye angles
  6077. var ex = -Vector3.Dot(this._xAxis, eye);
  6078. var ey = -Vector3.Dot(this._yAxis, eye);
  6079. var ez = -Vector3.Dot(this._zAxis, eye);
  6080. 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);
  6081. };
  6082. /**
  6083. * 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"
  6084. * This function works in right handed mode
  6085. * @param eye defines the final position of the entity
  6086. * @param target defines where the entity should look at
  6087. * @param up defines the up vector for the entity
  6088. * @returns the new matrix
  6089. */
  6090. Matrix.LookAtRH = function (eye, target, up) {
  6091. var result = Matrix.Zero();
  6092. Matrix.LookAtRHToRef(eye, target, up, result);
  6093. return result;
  6094. };
  6095. /**
  6096. * 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".
  6097. * This function works in right handed mode
  6098. * @param eye defines the final position of the entity
  6099. * @param target defines where the entity should look at
  6100. * @param up defines the up vector for the entity
  6101. * @param result defines the target matrix
  6102. */
  6103. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6104. // Z axis
  6105. eye.subtractToRef(target, this._zAxis);
  6106. this._zAxis.normalize();
  6107. // X axis
  6108. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6109. if (this._xAxis.lengthSquared() === 0) {
  6110. this._xAxis.x = 1.0;
  6111. }
  6112. else {
  6113. this._xAxis.normalize();
  6114. }
  6115. // Y axis
  6116. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6117. this._yAxis.normalize();
  6118. // Eye angles
  6119. var ex = -Vector3.Dot(this._xAxis, eye);
  6120. var ey = -Vector3.Dot(this._yAxis, eye);
  6121. var ez = -Vector3.Dot(this._zAxis, eye);
  6122. 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);
  6123. };
  6124. /**
  6125. * Create a left-handed orthographic projection matrix
  6126. * @param width defines the viewport width
  6127. * @param height defines the viewport height
  6128. * @param znear defines the near clip plane
  6129. * @param zfar defines the far clip plane
  6130. * @returns a new matrix as a left-handed orthographic projection matrix
  6131. */
  6132. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6133. var matrix = Matrix.Zero();
  6134. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6135. return matrix;
  6136. };
  6137. /**
  6138. * Store a left-handed orthographic projection to a given matrix
  6139. * @param width defines the viewport width
  6140. * @param height defines the viewport height
  6141. * @param znear defines the near clip plane
  6142. * @param zfar defines the far clip plane
  6143. * @param result defines the target matrix
  6144. */
  6145. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6146. var n = znear;
  6147. var f = zfar;
  6148. var a = 2.0 / width;
  6149. var b = 2.0 / height;
  6150. var c = 2.0 / (f - n);
  6151. var d = -(f + n) / (f - n);
  6152. 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);
  6153. };
  6154. /**
  6155. * Create a left-handed orthographic projection matrix
  6156. * @param left defines the viewport left coordinate
  6157. * @param right defines the viewport right coordinate
  6158. * @param bottom defines the viewport bottom coordinate
  6159. * @param top defines the viewport top coordinate
  6160. * @param znear defines the near clip plane
  6161. * @param zfar defines the far clip plane
  6162. * @returns a new matrix as a left-handed orthographic projection matrix
  6163. */
  6164. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6165. var matrix = Matrix.Zero();
  6166. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6167. return matrix;
  6168. };
  6169. /**
  6170. * Stores a left-handed orthographic projection into a given matrix
  6171. * @param left defines the viewport left coordinate
  6172. * @param right defines the viewport right coordinate
  6173. * @param bottom defines the viewport bottom coordinate
  6174. * @param top defines the viewport top coordinate
  6175. * @param znear defines the near clip plane
  6176. * @param zfar defines the far clip plane
  6177. * @param result defines the target matrix
  6178. */
  6179. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6180. var n = znear;
  6181. var f = zfar;
  6182. var a = 2.0 / (right - left);
  6183. var b = 2.0 / (top - bottom);
  6184. var c = 2.0 / (f - n);
  6185. var d = -(f + n) / (f - n);
  6186. var i0 = (left + right) / (left - right);
  6187. var i1 = (top + bottom) / (bottom - top);
  6188. 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);
  6189. };
  6190. /**
  6191. * Creates a right-handed orthographic projection matrix
  6192. * @param left defines the viewport left coordinate
  6193. * @param right defines the viewport right coordinate
  6194. * @param bottom defines the viewport bottom coordinate
  6195. * @param top defines the viewport top coordinate
  6196. * @param znear defines the near clip plane
  6197. * @param zfar defines the far clip plane
  6198. * @returns a new matrix as a right-handed orthographic projection matrix
  6199. */
  6200. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6201. var matrix = Matrix.Zero();
  6202. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6203. return matrix;
  6204. };
  6205. /**
  6206. * Stores a right-handed orthographic projection into a given matrix
  6207. * @param left defines the viewport left coordinate
  6208. * @param right defines the viewport right coordinate
  6209. * @param bottom defines the viewport bottom coordinate
  6210. * @param top defines the viewport top coordinate
  6211. * @param znear defines the near clip plane
  6212. * @param zfar defines the far clip plane
  6213. * @param result defines the target matrix
  6214. */
  6215. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6216. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6217. result.m[10] *= -1.0;
  6218. };
  6219. /**
  6220. * Creates a left-handed perspective projection matrix
  6221. * @param width defines the viewport width
  6222. * @param height defines the viewport height
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @returns a new matrix as a left-handed perspective projection matrix
  6226. */
  6227. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6228. var matrix = Matrix.Zero();
  6229. var n = znear;
  6230. var f = zfar;
  6231. var a = 2.0 * n / width;
  6232. var b = 2.0 * n / height;
  6233. var c = (f + n) / (f - n);
  6234. var d = -2.0 * f * n / (f - n);
  6235. 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);
  6236. return matrix;
  6237. };
  6238. /**
  6239. * Creates a left-handed perspective projection matrix
  6240. * @param fov defines the horizontal field of view
  6241. * @param aspect defines the aspect ratio
  6242. * @param znear defines the near clip plane
  6243. * @param zfar defines the far clip plane
  6244. * @returns a new matrix as a left-handed perspective projection matrix
  6245. */
  6246. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6247. var matrix = Matrix.Zero();
  6248. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6249. return matrix;
  6250. };
  6251. /**
  6252. * Stores a left-handed perspective projection into a given matrix
  6253. * @param fov defines the horizontal field of view
  6254. * @param aspect defines the aspect ratio
  6255. * @param znear defines the near clip plane
  6256. * @param zfar defines the far clip plane
  6257. * @param result defines the target matrix
  6258. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6259. */
  6260. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6261. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6262. var n = znear;
  6263. var f = zfar;
  6264. var t = 1.0 / (Math.tan(fov * 0.5));
  6265. var a = isVerticalFovFixed ? (t / aspect) : t;
  6266. var b = isVerticalFovFixed ? t : (t * aspect);
  6267. var c = (f + n) / (f - n);
  6268. var d = -2.0 * f * n / (f - n);
  6269. 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);
  6270. };
  6271. /**
  6272. * Creates a right-handed perspective projection matrix
  6273. * @param fov defines the horizontal field of view
  6274. * @param aspect defines the aspect ratio
  6275. * @param znear defines the near clip plane
  6276. * @param zfar defines the far clip plane
  6277. * @returns a new matrix as a right-handed perspective projection matrix
  6278. */
  6279. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6280. var matrix = Matrix.Zero();
  6281. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6282. return matrix;
  6283. };
  6284. /**
  6285. * Stores a right-handed perspective projection into a given matrix
  6286. * @param fov defines the horizontal field of view
  6287. * @param aspect defines the aspect ratio
  6288. * @param znear defines the near clip plane
  6289. * @param zfar defines the far clip plane
  6290. * @param result defines the target matrix
  6291. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6292. */
  6293. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6294. //alternatively this could be expressed as:
  6295. // m = PerspectiveFovLHToRef
  6296. // m[10] *= -1.0;
  6297. // m[11] *= -1.0;
  6298. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6299. var n = znear;
  6300. var f = zfar;
  6301. var t = 1.0 / (Math.tan(fov * 0.5));
  6302. var a = isVerticalFovFixed ? (t / aspect) : t;
  6303. var b = isVerticalFovFixed ? t : (t * aspect);
  6304. var c = -(f + n) / (f - n);
  6305. var d = -2 * f * n / (f - n);
  6306. 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);
  6307. };
  6308. /**
  6309. * Stores a perspective projection for WebVR info a given matrix
  6310. * @param fov defines the field of view
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @param result defines the target matrix
  6314. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6315. */
  6316. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6317. if (rightHanded === void 0) { rightHanded = false; }
  6318. var rightHandedFactor = rightHanded ? -1 : 1;
  6319. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6320. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6321. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6322. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6323. var xScale = 2.0 / (leftTan + rightTan);
  6324. var yScale = 2.0 / (upTan + downTan);
  6325. result.m[0] = xScale;
  6326. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6327. result.m[5] = yScale;
  6328. result.m[6] = result.m[7] = 0.0;
  6329. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6330. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6331. result.m[10] = -zfar / (znear - zfar);
  6332. result.m[11] = 1.0 * rightHandedFactor;
  6333. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6334. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6335. result._markAsUpdated();
  6336. };
  6337. /**
  6338. * Computes a complete transformation matrix
  6339. * @param viewport defines the viewport to use
  6340. * @param world defines the world matrix
  6341. * @param view defines the view matrix
  6342. * @param projection defines the projection matrix
  6343. * @param zmin defines the near clip plane
  6344. * @param zmax defines the far clip plane
  6345. * @returns the transformation matrix
  6346. */
  6347. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6348. var cw = viewport.width;
  6349. var ch = viewport.height;
  6350. var cx = viewport.x;
  6351. var cy = viewport.y;
  6352. 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);
  6353. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6354. };
  6355. /**
  6356. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6357. * @param matrix defines the matrix to use
  6358. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6359. */
  6360. Matrix.GetAsMatrix2x2 = function (matrix) {
  6361. return new Float32Array([
  6362. matrix.m[0], matrix.m[1],
  6363. matrix.m[4], matrix.m[5]
  6364. ]);
  6365. };
  6366. /**
  6367. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6368. * @param matrix defines the matrix to use
  6369. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6370. */
  6371. Matrix.GetAsMatrix3x3 = function (matrix) {
  6372. return new Float32Array([
  6373. matrix.m[0], matrix.m[1], matrix.m[2],
  6374. matrix.m[4], matrix.m[5], matrix.m[6],
  6375. matrix.m[8], matrix.m[9], matrix.m[10]
  6376. ]);
  6377. };
  6378. /**
  6379. * Compute the transpose of a given matrix
  6380. * @param matrix defines the matrix to transpose
  6381. * @returns the new matrix
  6382. */
  6383. Matrix.Transpose = function (matrix) {
  6384. var result = new Matrix();
  6385. Matrix.TransposeToRef(matrix, result);
  6386. return result;
  6387. };
  6388. /**
  6389. * Compute the transpose of a matrix and store it in a target matrix
  6390. * @param matrix defines the matrix to transpose
  6391. * @param result defines the target matrix
  6392. */
  6393. Matrix.TransposeToRef = function (matrix, result) {
  6394. result.m[0] = matrix.m[0];
  6395. result.m[1] = matrix.m[4];
  6396. result.m[2] = matrix.m[8];
  6397. result.m[3] = matrix.m[12];
  6398. result.m[4] = matrix.m[1];
  6399. result.m[5] = matrix.m[5];
  6400. result.m[6] = matrix.m[9];
  6401. result.m[7] = matrix.m[13];
  6402. result.m[8] = matrix.m[2];
  6403. result.m[9] = matrix.m[6];
  6404. result.m[10] = matrix.m[10];
  6405. result.m[11] = matrix.m[14];
  6406. result.m[12] = matrix.m[3];
  6407. result.m[13] = matrix.m[7];
  6408. result.m[14] = matrix.m[11];
  6409. result.m[15] = matrix.m[15];
  6410. };
  6411. /**
  6412. * Computes a reflection matrix from a plane
  6413. * @param plane defines the reflection plane
  6414. * @returns a new matrix
  6415. */
  6416. Matrix.Reflection = function (plane) {
  6417. var matrix = new Matrix();
  6418. Matrix.ReflectionToRef(plane, matrix);
  6419. return matrix;
  6420. };
  6421. /**
  6422. * Computes a reflection matrix from a plane
  6423. * @param plane defines the reflection plane
  6424. * @param result defines the target matrix
  6425. */
  6426. Matrix.ReflectionToRef = function (plane, result) {
  6427. plane.normalize();
  6428. var x = plane.normal.x;
  6429. var y = plane.normal.y;
  6430. var z = plane.normal.z;
  6431. var temp = -2 * x;
  6432. var temp2 = -2 * y;
  6433. var temp3 = -2 * z;
  6434. result.m[0] = (temp * x) + 1;
  6435. result.m[1] = temp2 * x;
  6436. result.m[2] = temp3 * x;
  6437. result.m[3] = 0.0;
  6438. result.m[4] = temp * y;
  6439. result.m[5] = (temp2 * y) + 1;
  6440. result.m[6] = temp3 * y;
  6441. result.m[7] = 0.0;
  6442. result.m[8] = temp * z;
  6443. result.m[9] = temp2 * z;
  6444. result.m[10] = (temp3 * z) + 1;
  6445. result.m[11] = 0.0;
  6446. result.m[12] = temp * plane.d;
  6447. result.m[13] = temp2 * plane.d;
  6448. result.m[14] = temp3 * plane.d;
  6449. result.m[15] = 1.0;
  6450. result._markAsUpdated();
  6451. };
  6452. /**
  6453. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6454. * @param xaxis defines the value of the 1st axis
  6455. * @param yaxis defines the value of the 2nd axis
  6456. * @param zaxis defines the value of the 3rd axis
  6457. * @param result defines the target matrix
  6458. */
  6459. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6460. result.m[0] = xaxis.x;
  6461. result.m[1] = xaxis.y;
  6462. result.m[2] = xaxis.z;
  6463. result.m[3] = 0.0;
  6464. result.m[4] = yaxis.x;
  6465. result.m[5] = yaxis.y;
  6466. result.m[6] = yaxis.z;
  6467. result.m[7] = 0.0;
  6468. result.m[8] = zaxis.x;
  6469. result.m[9] = zaxis.y;
  6470. result.m[10] = zaxis.z;
  6471. result.m[11] = 0.0;
  6472. result.m[12] = 0.0;
  6473. result.m[13] = 0.0;
  6474. result.m[14] = 0.0;
  6475. result.m[15] = 1.0;
  6476. result._markAsUpdated();
  6477. };
  6478. /**
  6479. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6480. * @param quat defines the quaternion to use
  6481. * @param result defines the target matrix
  6482. */
  6483. Matrix.FromQuaternionToRef = function (quat, result) {
  6484. var xx = quat.x * quat.x;
  6485. var yy = quat.y * quat.y;
  6486. var zz = quat.z * quat.z;
  6487. var xy = quat.x * quat.y;
  6488. var zw = quat.z * quat.w;
  6489. var zx = quat.z * quat.x;
  6490. var yw = quat.y * quat.w;
  6491. var yz = quat.y * quat.z;
  6492. var xw = quat.x * quat.w;
  6493. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6494. result.m[1] = 2.0 * (xy + zw);
  6495. result.m[2] = 2.0 * (zx - yw);
  6496. result.m[3] = 0.0;
  6497. result.m[4] = 2.0 * (xy - zw);
  6498. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6499. result.m[6] = 2.0 * (yz + xw);
  6500. result.m[7] = 0.0;
  6501. result.m[8] = 2.0 * (zx + yw);
  6502. result.m[9] = 2.0 * (yz - xw);
  6503. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6504. result.m[11] = 0.0;
  6505. result.m[12] = 0.0;
  6506. result.m[13] = 0.0;
  6507. result.m[14] = 0.0;
  6508. result.m[15] = 1.0;
  6509. result._markAsUpdated();
  6510. };
  6511. Matrix._tempQuaternion = new Quaternion();
  6512. Matrix._xAxis = Vector3.Zero();
  6513. Matrix._yAxis = Vector3.Zero();
  6514. Matrix._zAxis = Vector3.Zero();
  6515. Matrix._updateFlagSeed = 0;
  6516. Matrix._identityReadOnly = Matrix.Identity();
  6517. return Matrix;
  6518. }());
  6519. BABYLON.Matrix = Matrix;
  6520. var Plane = /** @class */ (function () {
  6521. /**
  6522. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6523. */
  6524. function Plane(a, b, c, d) {
  6525. this.normal = new Vector3(a, b, c);
  6526. this.d = d;
  6527. }
  6528. /**
  6529. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6530. */
  6531. Plane.prototype.asArray = function () {
  6532. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6533. };
  6534. // Methods
  6535. /**
  6536. * Returns a new plane copied from the current Plane.
  6537. */
  6538. Plane.prototype.clone = function () {
  6539. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6540. };
  6541. /**
  6542. * Returns the string "Plane".
  6543. */
  6544. Plane.prototype.getClassName = function () {
  6545. return "Plane";
  6546. };
  6547. /**
  6548. * Returns the Plane hash code.
  6549. */
  6550. Plane.prototype.getHashCode = function () {
  6551. var hash = this.normal.getHashCode();
  6552. hash = (hash * 397) ^ (this.d || 0);
  6553. return hash;
  6554. };
  6555. /**
  6556. * Normalize the current Plane in place.
  6557. * Returns the updated Plane.
  6558. */
  6559. Plane.prototype.normalize = function () {
  6560. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6561. var magnitude = 0.0;
  6562. if (norm !== 0) {
  6563. magnitude = 1.0 / norm;
  6564. }
  6565. this.normal.x *= magnitude;
  6566. this.normal.y *= magnitude;
  6567. this.normal.z *= magnitude;
  6568. this.d *= magnitude;
  6569. return this;
  6570. };
  6571. /**
  6572. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6573. */
  6574. Plane.prototype.transform = function (transformation) {
  6575. var transposedMatrix = Matrix.Transpose(transformation);
  6576. var x = this.normal.x;
  6577. var y = this.normal.y;
  6578. var z = this.normal.z;
  6579. var d = this.d;
  6580. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6581. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6582. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6583. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6584. return new Plane(normalX, normalY, normalZ, finalD);
  6585. };
  6586. /**
  6587. * Returns the dot product (float) of the point coordinates and the plane normal.
  6588. */
  6589. Plane.prototype.dotCoordinate = function (point) {
  6590. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6591. };
  6592. /**
  6593. * Updates the current Plane from the plane defined by the three given points.
  6594. * Returns the updated Plane.
  6595. */
  6596. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6597. var x1 = point2.x - point1.x;
  6598. var y1 = point2.y - point1.y;
  6599. var z1 = point2.z - point1.z;
  6600. var x2 = point3.x - point1.x;
  6601. var y2 = point3.y - point1.y;
  6602. var z2 = point3.z - point1.z;
  6603. var yz = (y1 * z2) - (z1 * y2);
  6604. var xz = (z1 * x2) - (x1 * z2);
  6605. var xy = (x1 * y2) - (y1 * x2);
  6606. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6607. var invPyth;
  6608. if (pyth !== 0) {
  6609. invPyth = 1.0 / pyth;
  6610. }
  6611. else {
  6612. invPyth = 0.0;
  6613. }
  6614. this.normal.x = yz * invPyth;
  6615. this.normal.y = xz * invPyth;
  6616. this.normal.z = xy * invPyth;
  6617. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6618. return this;
  6619. };
  6620. /**
  6621. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6622. */
  6623. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6624. var dot = Vector3.Dot(this.normal, direction);
  6625. return (dot <= epsilon);
  6626. };
  6627. /**
  6628. * Returns the signed distance (float) from the given point to the Plane.
  6629. */
  6630. Plane.prototype.signedDistanceTo = function (point) {
  6631. return Vector3.Dot(point, this.normal) + this.d;
  6632. };
  6633. // Statics
  6634. /**
  6635. * Returns a new Plane from the given array.
  6636. */
  6637. Plane.FromArray = function (array) {
  6638. return new Plane(array[0], array[1], array[2], array[3]);
  6639. };
  6640. /**
  6641. * Returns a new Plane defined by the three given points.
  6642. */
  6643. Plane.FromPoints = function (point1, point2, point3) {
  6644. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6645. result.copyFromPoints(point1, point2, point3);
  6646. return result;
  6647. };
  6648. /**
  6649. * Returns a new Plane the normal vector to this plane at the given origin point.
  6650. * Note : the vector "normal" is updated because normalized.
  6651. */
  6652. Plane.FromPositionAndNormal = function (origin, normal) {
  6653. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6654. normal.normalize();
  6655. result.normal = normal;
  6656. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6657. return result;
  6658. };
  6659. /**
  6660. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6661. */
  6662. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6663. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6664. return Vector3.Dot(point, normal) + d;
  6665. };
  6666. return Plane;
  6667. }());
  6668. BABYLON.Plane = Plane;
  6669. var Viewport = /** @class */ (function () {
  6670. /**
  6671. * Creates a Viewport object located at (x, y) and sized (width, height).
  6672. */
  6673. function Viewport(x, y, width, height) {
  6674. this.x = x;
  6675. this.y = y;
  6676. this.width = width;
  6677. this.height = height;
  6678. }
  6679. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6680. if (renderWidthOrEngine.getRenderWidth) {
  6681. var engine = renderWidthOrEngine;
  6682. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6683. }
  6684. var renderWidth = renderWidthOrEngine;
  6685. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6686. };
  6687. /**
  6688. * Returns a new Viewport copied from the current one.
  6689. */
  6690. Viewport.prototype.clone = function () {
  6691. return new Viewport(this.x, this.y, this.width, this.height);
  6692. };
  6693. return Viewport;
  6694. }());
  6695. BABYLON.Viewport = Viewport;
  6696. var Frustum = /** @class */ (function () {
  6697. function Frustum() {
  6698. }
  6699. /**
  6700. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6701. */
  6702. Frustum.GetPlanes = function (transform) {
  6703. var frustumPlanes = [];
  6704. for (var index = 0; index < 6; index++) {
  6705. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6706. }
  6707. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6708. return frustumPlanes;
  6709. };
  6710. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6711. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6712. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6713. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6714. frustumPlane.d = transform.m[15] + transform.m[14];
  6715. frustumPlane.normalize();
  6716. };
  6717. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6718. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6719. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6720. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6721. frustumPlane.d = transform.m[15] - transform.m[14];
  6722. frustumPlane.normalize();
  6723. };
  6724. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6725. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6726. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6727. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6728. frustumPlane.d = transform.m[15] + transform.m[12];
  6729. frustumPlane.normalize();
  6730. };
  6731. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6732. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6733. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6734. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6735. frustumPlane.d = transform.m[15] - transform.m[12];
  6736. frustumPlane.normalize();
  6737. };
  6738. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6739. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6740. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6741. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6742. frustumPlane.d = transform.m[15] - transform.m[13];
  6743. frustumPlane.normalize();
  6744. };
  6745. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6746. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6747. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6748. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6749. frustumPlane.d = transform.m[15] + transform.m[13];
  6750. frustumPlane.normalize();
  6751. };
  6752. /**
  6753. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6754. */
  6755. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6756. // Near
  6757. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6758. // Far
  6759. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6760. // Left
  6761. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6762. // Right
  6763. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6764. // Top
  6765. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6766. // Bottom
  6767. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6768. };
  6769. return Frustum;
  6770. }());
  6771. BABYLON.Frustum = Frustum;
  6772. /** Defines supported spaces */
  6773. var Space;
  6774. (function (Space) {
  6775. /** Local (object) space */
  6776. Space[Space["LOCAL"] = 0] = "LOCAL";
  6777. /** World space */
  6778. Space[Space["WORLD"] = 1] = "WORLD";
  6779. /** Bone space */
  6780. Space[Space["BONE"] = 2] = "BONE";
  6781. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6782. /** Defines the 3 main axes */
  6783. var Axis = /** @class */ (function () {
  6784. function Axis() {
  6785. }
  6786. /** X axis */
  6787. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6788. /** Y axis */
  6789. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6790. /** Z axis */
  6791. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6792. return Axis;
  6793. }());
  6794. BABYLON.Axis = Axis;
  6795. ;
  6796. var BezierCurve = /** @class */ (function () {
  6797. function BezierCurve() {
  6798. }
  6799. /**
  6800. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6801. */
  6802. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6803. // Extract X (which is equal to time here)
  6804. var f0 = 1 - 3 * x2 + 3 * x1;
  6805. var f1 = 3 * x2 - 6 * x1;
  6806. var f2 = 3 * x1;
  6807. var refinedT = t;
  6808. for (var i = 0; i < 5; i++) {
  6809. var refinedT2 = refinedT * refinedT;
  6810. var refinedT3 = refinedT2 * refinedT;
  6811. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6812. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6813. refinedT -= (x - t) * slope;
  6814. refinedT = Math.min(1, Math.max(0, refinedT));
  6815. }
  6816. // Resolve cubic bezier for the given x
  6817. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6818. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6819. Math.pow(refinedT, 3);
  6820. };
  6821. return BezierCurve;
  6822. }());
  6823. BABYLON.BezierCurve = BezierCurve;
  6824. /**
  6825. * Defines potential orientation for back face culling
  6826. */
  6827. var Orientation;
  6828. (function (Orientation) {
  6829. /**
  6830. * Clockwise
  6831. */
  6832. Orientation[Orientation["CW"] = 0] = "CW";
  6833. /** Counter clockwise */
  6834. Orientation[Orientation["CCW"] = 1] = "CCW";
  6835. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6836. /**
  6837. * Defines angle representation
  6838. */
  6839. var Angle = /** @class */ (function () {
  6840. /**
  6841. * Creates an Angle object of "radians" radians (float).
  6842. */
  6843. function Angle(radians) {
  6844. this._radians = radians;
  6845. if (this._radians < 0.0)
  6846. this._radians += (2.0 * Math.PI);
  6847. }
  6848. /**
  6849. * Get value in degrees
  6850. * @returns the Angle value in degrees (float)
  6851. */
  6852. Angle.prototype.degrees = function () {
  6853. return this._radians * 180.0 / Math.PI;
  6854. };
  6855. /**
  6856. * Get value in radians
  6857. * @returns the Angle value in radians (float)
  6858. */
  6859. Angle.prototype.radians = function () {
  6860. return this._radians;
  6861. };
  6862. /**
  6863. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6864. * @param a defines first vector
  6865. * @param b defines second vector
  6866. * @returns a new Angle
  6867. */
  6868. Angle.BetweenTwoPoints = function (a, b) {
  6869. var delta = b.subtract(a);
  6870. var theta = Math.atan2(delta.y, delta.x);
  6871. return new Angle(theta);
  6872. };
  6873. /**
  6874. * Gets a new Angle object from the given float in radians
  6875. * @param radians defines the angle value in radians
  6876. * @returns a new Angle
  6877. */
  6878. Angle.FromRadians = function (radians) {
  6879. return new Angle(radians);
  6880. };
  6881. /**
  6882. * Gets a new Angle object from the given float in degrees
  6883. * @param degrees defines the angle value in degrees
  6884. * @returns a new Angle
  6885. */
  6886. Angle.FromDegrees = function (degrees) {
  6887. return new Angle(degrees * Math.PI / 180.0);
  6888. };
  6889. return Angle;
  6890. }());
  6891. BABYLON.Angle = Angle;
  6892. var Arc2 = /** @class */ (function () {
  6893. /**
  6894. * Creates an Arc object from the three given points : start, middle and end.
  6895. */
  6896. function Arc2(startPoint, midPoint, endPoint) {
  6897. this.startPoint = startPoint;
  6898. this.midPoint = midPoint;
  6899. this.endPoint = endPoint;
  6900. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6901. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6902. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6903. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6904. 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);
  6905. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6906. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6907. var a1 = this.startAngle.degrees();
  6908. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6909. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6910. // angles correction
  6911. if (a2 - a1 > +180.0)
  6912. a2 -= 360.0;
  6913. if (a2 - a1 < -180.0)
  6914. a2 += 360.0;
  6915. if (a3 - a2 > +180.0)
  6916. a3 -= 360.0;
  6917. if (a3 - a2 < -180.0)
  6918. a3 += 360.0;
  6919. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6920. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6921. }
  6922. return Arc2;
  6923. }());
  6924. BABYLON.Arc2 = Arc2;
  6925. var Path2 = /** @class */ (function () {
  6926. /**
  6927. * Creates a Path2 object from the starting 2D coordinates x and y.
  6928. */
  6929. function Path2(x, y) {
  6930. this._points = new Array();
  6931. this._length = 0.0;
  6932. this.closed = false;
  6933. this._points.push(new Vector2(x, y));
  6934. }
  6935. /**
  6936. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6937. * Returns the updated Path2.
  6938. */
  6939. Path2.prototype.addLineTo = function (x, y) {
  6940. if (this.closed) {
  6941. return this;
  6942. }
  6943. var newPoint = new Vector2(x, y);
  6944. var previousPoint = this._points[this._points.length - 1];
  6945. this._points.push(newPoint);
  6946. this._length += newPoint.subtract(previousPoint).length();
  6947. return this;
  6948. };
  6949. /**
  6950. * 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.
  6951. * Returns the updated Path2.
  6952. */
  6953. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6954. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6955. if (this.closed) {
  6956. return this;
  6957. }
  6958. var startPoint = this._points[this._points.length - 1];
  6959. var midPoint = new Vector2(midX, midY);
  6960. var endPoint = new Vector2(endX, endY);
  6961. var arc = new Arc2(startPoint, midPoint, endPoint);
  6962. var increment = arc.angle.radians() / numberOfSegments;
  6963. if (arc.orientation === Orientation.CW)
  6964. increment *= -1;
  6965. var currentAngle = arc.startAngle.radians() + increment;
  6966. for (var i = 0; i < numberOfSegments; i++) {
  6967. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6968. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6969. this.addLineTo(x, y);
  6970. currentAngle += increment;
  6971. }
  6972. return this;
  6973. };
  6974. /**
  6975. * Closes the Path2.
  6976. * Returns the Path2.
  6977. */
  6978. Path2.prototype.close = function () {
  6979. this.closed = true;
  6980. return this;
  6981. };
  6982. /**
  6983. * Returns the Path2 total length (float).
  6984. */
  6985. Path2.prototype.length = function () {
  6986. var result = this._length;
  6987. if (!this.closed) {
  6988. var lastPoint = this._points[this._points.length - 1];
  6989. var firstPoint = this._points[0];
  6990. result += (firstPoint.subtract(lastPoint).length());
  6991. }
  6992. return result;
  6993. };
  6994. /**
  6995. * Returns the Path2 internal array of points.
  6996. */
  6997. Path2.prototype.getPoints = function () {
  6998. return this._points;
  6999. };
  7000. /**
  7001. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7002. */
  7003. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7004. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7005. return Vector2.Zero();
  7006. }
  7007. var lengthPosition = normalizedLengthPosition * this.length();
  7008. var previousOffset = 0;
  7009. for (var i = 0; i < this._points.length; i++) {
  7010. var j = (i + 1) % this._points.length;
  7011. var a = this._points[i];
  7012. var b = this._points[j];
  7013. var bToA = b.subtract(a);
  7014. var nextOffset = (bToA.length() + previousOffset);
  7015. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7016. var dir = bToA.normalize();
  7017. var localOffset = lengthPosition - previousOffset;
  7018. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7019. }
  7020. previousOffset = nextOffset;
  7021. }
  7022. return Vector2.Zero();
  7023. };
  7024. /**
  7025. * Returns a new Path2 starting at the coordinates (x, y).
  7026. */
  7027. Path2.StartingAt = function (x, y) {
  7028. return new Path2(x, y);
  7029. };
  7030. return Path2;
  7031. }());
  7032. BABYLON.Path2 = Path2;
  7033. var Path3D = /** @class */ (function () {
  7034. /**
  7035. * new Path3D(path, normal, raw)
  7036. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7037. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7038. * path : an array of Vector3, the curve axis of the Path3D
  7039. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7040. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7041. */
  7042. function Path3D(path, firstNormal, raw) {
  7043. if (firstNormal === void 0) { firstNormal = null; }
  7044. this.path = path;
  7045. this._curve = new Array();
  7046. this._distances = new Array();
  7047. this._tangents = new Array();
  7048. this._normals = new Array();
  7049. this._binormals = new Array();
  7050. for (var p = 0; p < path.length; p++) {
  7051. this._curve[p] = path[p].clone(); // hard copy
  7052. }
  7053. this._raw = raw || false;
  7054. this._compute(firstNormal);
  7055. }
  7056. /**
  7057. * Returns the Path3D array of successive Vector3 designing its curve.
  7058. */
  7059. Path3D.prototype.getCurve = function () {
  7060. return this._curve;
  7061. };
  7062. /**
  7063. * Returns an array populated with tangent vectors on each Path3D curve point.
  7064. */
  7065. Path3D.prototype.getTangents = function () {
  7066. return this._tangents;
  7067. };
  7068. /**
  7069. * Returns an array populated with normal vectors on each Path3D curve point.
  7070. */
  7071. Path3D.prototype.getNormals = function () {
  7072. return this._normals;
  7073. };
  7074. /**
  7075. * Returns an array populated with binormal vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getBinormals = function () {
  7078. return this._binormals;
  7079. };
  7080. /**
  7081. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7082. */
  7083. Path3D.prototype.getDistances = function () {
  7084. return this._distances;
  7085. };
  7086. /**
  7087. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7088. * Returns the same object updated.
  7089. */
  7090. Path3D.prototype.update = function (path, firstNormal) {
  7091. if (firstNormal === void 0) { firstNormal = null; }
  7092. for (var p = 0; p < path.length; p++) {
  7093. this._curve[p].x = path[p].x;
  7094. this._curve[p].y = path[p].y;
  7095. this._curve[p].z = path[p].z;
  7096. }
  7097. this._compute(firstNormal);
  7098. return this;
  7099. };
  7100. // private function compute() : computes tangents, normals and binormals
  7101. Path3D.prototype._compute = function (firstNormal) {
  7102. var l = this._curve.length;
  7103. // first and last tangents
  7104. this._tangents[0] = this._getFirstNonNullVector(0);
  7105. if (!this._raw) {
  7106. this._tangents[0].normalize();
  7107. }
  7108. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7109. if (!this._raw) {
  7110. this._tangents[l - 1].normalize();
  7111. }
  7112. // normals and binormals at first point : arbitrary vector with _normalVector()
  7113. var tg0 = this._tangents[0];
  7114. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7115. this._normals[0] = pp0;
  7116. if (!this._raw) {
  7117. this._normals[0].normalize();
  7118. }
  7119. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7120. if (!this._raw) {
  7121. this._binormals[0].normalize();
  7122. }
  7123. this._distances[0] = 0.0;
  7124. // normals and binormals : next points
  7125. var prev; // previous vector (segment)
  7126. var cur; // current vector (segment)
  7127. var curTang; // current tangent
  7128. // previous normal
  7129. var prevBinor; // previous binormal
  7130. for (var i = 1; i < l; i++) {
  7131. // tangents
  7132. prev = this._getLastNonNullVector(i);
  7133. if (i < l - 1) {
  7134. cur = this._getFirstNonNullVector(i);
  7135. this._tangents[i] = prev.add(cur);
  7136. this._tangents[i].normalize();
  7137. }
  7138. this._distances[i] = this._distances[i - 1] + prev.length();
  7139. // normals and binormals
  7140. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7141. curTang = this._tangents[i];
  7142. prevBinor = this._binormals[i - 1];
  7143. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7144. if (!this._raw) {
  7145. this._normals[i].normalize();
  7146. }
  7147. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7148. if (!this._raw) {
  7149. this._binormals[i].normalize();
  7150. }
  7151. }
  7152. };
  7153. // private function getFirstNonNullVector(index)
  7154. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7155. Path3D.prototype._getFirstNonNullVector = function (index) {
  7156. var i = 1;
  7157. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7158. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7159. i++;
  7160. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7161. }
  7162. return nNVector;
  7163. };
  7164. // private function getLastNonNullVector(index)
  7165. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7166. Path3D.prototype._getLastNonNullVector = function (index) {
  7167. var i = 1;
  7168. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7169. while (nLVector.length() === 0 && index > i + 1) {
  7170. i++;
  7171. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7172. }
  7173. return nLVector;
  7174. };
  7175. // private function normalVector(v0, vt, va) :
  7176. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7177. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7178. Path3D.prototype._normalVector = function (v0, vt, va) {
  7179. var normal0;
  7180. var tgl = vt.length();
  7181. if (tgl === 0.0) {
  7182. tgl = 1.0;
  7183. }
  7184. if (va === undefined || va === null) {
  7185. var point;
  7186. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7187. point = new Vector3(0.0, -1.0, 0.0);
  7188. }
  7189. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7190. point = new Vector3(1.0, 0.0, 0.0);
  7191. }
  7192. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7193. point = new Vector3(0.0, 0.0, 1.0);
  7194. }
  7195. else {
  7196. point = Vector3.Zero();
  7197. }
  7198. normal0 = Vector3.Cross(vt, point);
  7199. }
  7200. else {
  7201. normal0 = Vector3.Cross(vt, va);
  7202. Vector3.CrossToRef(normal0, vt, normal0);
  7203. }
  7204. normal0.normalize();
  7205. return normal0;
  7206. };
  7207. return Path3D;
  7208. }());
  7209. BABYLON.Path3D = Path3D;
  7210. var Curve3 = /** @class */ (function () {
  7211. /**
  7212. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7213. * A Curve3 is designed from a series of successive Vector3.
  7214. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7215. */
  7216. function Curve3(points) {
  7217. this._length = 0.0;
  7218. this._points = points;
  7219. this._length = this._computeLength(points);
  7220. }
  7221. /**
  7222. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7223. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7224. * @param v1 (Vector3) the control point
  7225. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7226. * @param nbPoints (integer) the wanted number of points in the curve
  7227. */
  7228. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7229. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7230. var bez = new Array();
  7231. var equation = function (t, val0, val1, val2) {
  7232. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7233. return res;
  7234. };
  7235. for (var i = 0; i <= nbPoints; i++) {
  7236. 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)));
  7237. }
  7238. return new Curve3(bez);
  7239. };
  7240. /**
  7241. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7242. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7243. * @param v1 (Vector3) the first control point
  7244. * @param v2 (Vector3) the second control point
  7245. * @param v3 (Vector3) the end point of the Cubic Bezier
  7246. * @param nbPoints (integer) the wanted number of points in the curve
  7247. */
  7248. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7249. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7250. var bez = new Array();
  7251. var equation = function (t, val0, val1, val2, val3) {
  7252. 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;
  7253. return res;
  7254. };
  7255. for (var i = 0; i <= nbPoints; i++) {
  7256. 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)));
  7257. }
  7258. return new Curve3(bez);
  7259. };
  7260. /**
  7261. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7262. * @param p1 (Vector3) the origin point of the Hermite Spline
  7263. * @param t1 (Vector3) the tangent vector at the origin point
  7264. * @param p2 (Vector3) the end point of the Hermite Spline
  7265. * @param t2 (Vector3) the tangent vector at the end point
  7266. * @param nbPoints (integer) the wanted number of points in the curve
  7267. */
  7268. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7269. var hermite = new Array();
  7270. var step = 1.0 / nbPoints;
  7271. for (var i = 0; i <= nbPoints; i++) {
  7272. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7273. }
  7274. return new Curve3(hermite);
  7275. };
  7276. /**
  7277. * Returns a Curve3 object along a CatmullRom Spline curve :
  7278. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7279. * @param nbPoints (integer) the wanted number of points between each curve control points
  7280. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7281. */
  7282. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7283. var catmullRom = new Array();
  7284. var step = 1.0 / nbPoints;
  7285. var amount = 0.0;
  7286. if (closed) {
  7287. var pointsCount = points.length;
  7288. for (var i = 0; i < pointsCount; i++) {
  7289. amount = 0;
  7290. for (var c = 0; c < nbPoints; c++) {
  7291. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7292. amount += step;
  7293. }
  7294. }
  7295. catmullRom.push(catmullRom[0]);
  7296. }
  7297. else {
  7298. var totalPoints = new Array();
  7299. totalPoints.push(points[0].clone());
  7300. Array.prototype.push.apply(totalPoints, points);
  7301. totalPoints.push(points[points.length - 1].clone());
  7302. for (var i = 0; i < totalPoints.length - 3; i++) {
  7303. amount = 0;
  7304. for (var c = 0; c < nbPoints; c++) {
  7305. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7306. amount += step;
  7307. }
  7308. }
  7309. i--;
  7310. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7311. }
  7312. return new Curve3(catmullRom);
  7313. };
  7314. /**
  7315. * Returns the Curve3 stored array of successive Vector3
  7316. */
  7317. Curve3.prototype.getPoints = function () {
  7318. return this._points;
  7319. };
  7320. /**
  7321. * Returns the computed length (float) of the curve.
  7322. */
  7323. Curve3.prototype.length = function () {
  7324. return this._length;
  7325. };
  7326. /**
  7327. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7328. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7329. * curveA and curveB keep unchanged.
  7330. */
  7331. Curve3.prototype.continue = function (curve) {
  7332. var lastPoint = this._points[this._points.length - 1];
  7333. var continuedPoints = this._points.slice();
  7334. var curvePoints = curve.getPoints();
  7335. for (var i = 1; i < curvePoints.length; i++) {
  7336. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7337. }
  7338. var continuedCurve = new Curve3(continuedPoints);
  7339. return continuedCurve;
  7340. };
  7341. Curve3.prototype._computeLength = function (path) {
  7342. var l = 0;
  7343. for (var i = 1; i < path.length; i++) {
  7344. l += (path[i].subtract(path[i - 1])).length();
  7345. }
  7346. return l;
  7347. };
  7348. return Curve3;
  7349. }());
  7350. BABYLON.Curve3 = Curve3;
  7351. // Vertex formats
  7352. var PositionNormalVertex = /** @class */ (function () {
  7353. function PositionNormalVertex(position, normal) {
  7354. if (position === void 0) { position = Vector3.Zero(); }
  7355. if (normal === void 0) { normal = Vector3.Up(); }
  7356. this.position = position;
  7357. this.normal = normal;
  7358. }
  7359. PositionNormalVertex.prototype.clone = function () {
  7360. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7361. };
  7362. return PositionNormalVertex;
  7363. }());
  7364. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7365. var PositionNormalTextureVertex = /** @class */ (function () {
  7366. function PositionNormalTextureVertex(position, normal, uv) {
  7367. if (position === void 0) { position = Vector3.Zero(); }
  7368. if (normal === void 0) { normal = Vector3.Up(); }
  7369. if (uv === void 0) { uv = Vector2.Zero(); }
  7370. this.position = position;
  7371. this.normal = normal;
  7372. this.uv = uv;
  7373. }
  7374. PositionNormalTextureVertex.prototype.clone = function () {
  7375. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7376. };
  7377. return PositionNormalTextureVertex;
  7378. }());
  7379. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7380. // Temporary pre-allocated objects for engine internal use
  7381. // usage in any internal function :
  7382. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7383. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7384. var Tmp = /** @class */ (function () {
  7385. function Tmp() {
  7386. }
  7387. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7388. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7389. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7390. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7391. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7392. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7393. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7394. Matrix.Zero(), Matrix.Zero(),
  7395. Matrix.Zero(), Matrix.Zero(),
  7396. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7397. return Tmp;
  7398. }());
  7399. BABYLON.Tmp = Tmp;
  7400. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7401. var MathTmp = /** @class */ (function () {
  7402. function MathTmp() {
  7403. }
  7404. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7405. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7406. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7407. return MathTmp;
  7408. }());
  7409. })(BABYLON || (BABYLON = {}));
  7410. //# sourceMappingURL=babylon.math.js.map
  7411. var BABYLON;
  7412. (function (BABYLON) {
  7413. var Scalar = /** @class */ (function () {
  7414. function Scalar() {
  7415. }
  7416. /**
  7417. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7418. */
  7419. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7420. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7421. var num = a - b;
  7422. return -epsilon <= num && num <= epsilon;
  7423. };
  7424. /**
  7425. * Returns a string : the upper case translation of the number i to hexadecimal.
  7426. */
  7427. Scalar.ToHex = function (i) {
  7428. var str = i.toString(16);
  7429. if (i <= 15) {
  7430. return ("0" + str).toUpperCase();
  7431. }
  7432. return str.toUpperCase();
  7433. };
  7434. /**
  7435. * Returns -1 if value is negative and +1 is value is positive.
  7436. * Returns the value itself if it's equal to zero.
  7437. */
  7438. Scalar.Sign = function (value) {
  7439. value = +value; // convert to a number
  7440. if (value === 0 || isNaN(value))
  7441. return value;
  7442. return value > 0 ? 1 : -1;
  7443. };
  7444. /**
  7445. * Returns the value itself if it's between min and max.
  7446. * Returns min if the value is lower than min.
  7447. * Returns max if the value is greater than max.
  7448. */
  7449. Scalar.Clamp = function (value, min, max) {
  7450. if (min === void 0) { min = 0; }
  7451. if (max === void 0) { max = 1; }
  7452. return Math.min(max, Math.max(min, value));
  7453. };
  7454. /**
  7455. * Returns the log2 of value.
  7456. */
  7457. Scalar.Log2 = function (value) {
  7458. return Math.log(value) * Math.LOG2E;
  7459. };
  7460. /**
  7461. * Loops the value, so that it is never larger than length and never smaller than 0.
  7462. *
  7463. * This is similar to the modulo operator but it works with floating point numbers.
  7464. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7465. * With t = 5 and length = 2.5, the result would be 0.0.
  7466. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7467. */
  7468. Scalar.Repeat = function (value, length) {
  7469. return value - Math.floor(value / length) * length;
  7470. };
  7471. /**
  7472. * Normalize the value between 0.0 and 1.0 using min and max values
  7473. */
  7474. Scalar.Normalize = function (value, min, max) {
  7475. return (value - min) / (max - min);
  7476. };
  7477. /**
  7478. * Denormalize the value from 0.0 and 1.0 using min and max values
  7479. */
  7480. Scalar.Denormalize = function (normalized, min, max) {
  7481. return (normalized * (max - min) + min);
  7482. };
  7483. /**
  7484. * Calculates the shortest difference between two given angles given in degrees.
  7485. */
  7486. Scalar.DeltaAngle = function (current, target) {
  7487. var num = Scalar.Repeat(target - current, 360.0);
  7488. if (num > 180.0) {
  7489. num -= 360.0;
  7490. }
  7491. return num;
  7492. };
  7493. /**
  7494. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7495. *
  7496. * The returned value will move back and forth between 0 and length
  7497. */
  7498. Scalar.PingPong = function (tx, length) {
  7499. var t = Scalar.Repeat(tx, length * 2.0);
  7500. return length - Math.abs(t - length);
  7501. };
  7502. /**
  7503. * Interpolates between min and max with smoothing at the limits.
  7504. *
  7505. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7506. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7507. */
  7508. Scalar.SmoothStep = function (from, to, tx) {
  7509. var t = Scalar.Clamp(tx);
  7510. t = -2.0 * t * t * t + 3.0 * t * t;
  7511. return to * t + from * (1.0 - t);
  7512. };
  7513. /**
  7514. * Moves a value current towards target.
  7515. *
  7516. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7517. * Negative values of maxDelta pushes the value away from target.
  7518. */
  7519. Scalar.MoveTowards = function (current, target, maxDelta) {
  7520. var result = 0;
  7521. if (Math.abs(target - current) <= maxDelta) {
  7522. result = target;
  7523. }
  7524. else {
  7525. result = current + Scalar.Sign(target - current) * maxDelta;
  7526. }
  7527. return result;
  7528. };
  7529. /**
  7530. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7531. *
  7532. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7533. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7534. */
  7535. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7536. var num = Scalar.DeltaAngle(current, target);
  7537. var result = 0;
  7538. if (-maxDelta < num && num < maxDelta) {
  7539. result = target;
  7540. }
  7541. else {
  7542. target = current + num;
  7543. result = Scalar.MoveTowards(current, target, maxDelta);
  7544. }
  7545. return result;
  7546. };
  7547. /**
  7548. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7549. */
  7550. Scalar.Lerp = function (start, end, amount) {
  7551. return start + ((end - start) * amount);
  7552. };
  7553. /**
  7554. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7555. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7556. */
  7557. Scalar.LerpAngle = function (start, end, amount) {
  7558. var num = Scalar.Repeat(end - start, 360.0);
  7559. if (num > 180.0) {
  7560. num -= 360.0;
  7561. }
  7562. return start + num * Scalar.Clamp(amount);
  7563. };
  7564. /**
  7565. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7566. */
  7567. Scalar.InverseLerp = function (a, b, value) {
  7568. var result = 0;
  7569. if (a != b) {
  7570. result = Scalar.Clamp((value - a) / (b - a));
  7571. }
  7572. else {
  7573. result = 0.0;
  7574. }
  7575. return result;
  7576. };
  7577. /**
  7578. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7579. */
  7580. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7581. var squared = amount * amount;
  7582. var cubed = amount * squared;
  7583. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7584. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7585. var part3 = (cubed - (2.0 * squared)) + amount;
  7586. var part4 = cubed - squared;
  7587. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7588. };
  7589. /**
  7590. * Returns a random float number between and min and max values
  7591. */
  7592. Scalar.RandomRange = function (min, max) {
  7593. if (min === max)
  7594. return min;
  7595. return ((Math.random() * (max - min)) + min);
  7596. };
  7597. /**
  7598. * This function returns percentage of a number in a given range.
  7599. *
  7600. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7601. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7602. */
  7603. Scalar.RangeToPercent = function (number, min, max) {
  7604. return ((number - min) / (max - min));
  7605. };
  7606. /**
  7607. * This function returns number that corresponds to the percentage in a given range.
  7608. *
  7609. * PercentToRange(0.34,0,100) will return 34.
  7610. */
  7611. Scalar.PercentToRange = function (percent, min, max) {
  7612. return ((max - min) * percent + min);
  7613. };
  7614. /**
  7615. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7616. * @param angle The angle to normalize in radian.
  7617. * @return The converted angle.
  7618. */
  7619. Scalar.NormalizeRadians = function (angle) {
  7620. // More precise but slower version kept for reference.
  7621. // angle = angle % Tools.TwoPi;
  7622. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7623. //if (angle > Math.PI) {
  7624. // angle -= Tools.TwoPi;
  7625. //}
  7626. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7627. return angle;
  7628. };
  7629. /**
  7630. * Two pi constants convenient for computation.
  7631. */
  7632. Scalar.TwoPi = Math.PI * 2;
  7633. return Scalar;
  7634. }());
  7635. BABYLON.Scalar = Scalar;
  7636. })(BABYLON || (BABYLON = {}));
  7637. //# sourceMappingURL=babylon.math.scalar.js.map
  7638. //# sourceMappingURL=babylon.mixins.js.map
  7639. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7640. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7641. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7642. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7643. //# sourceMappingURL=babylon.webgl2.js.map
  7644. var BABYLON;
  7645. (function (BABYLON) {
  7646. var __decoratorInitialStore = {};
  7647. var __mergedStore = {};
  7648. var _copySource = function (creationFunction, source, instanciate) {
  7649. var destination = creationFunction();
  7650. // Tags
  7651. if (BABYLON.Tags) {
  7652. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7653. }
  7654. var classStore = getMergedStore(destination);
  7655. // Properties
  7656. for (var property in classStore) {
  7657. var propertyDescriptor = classStore[property];
  7658. var sourceProperty = source[property];
  7659. var propertyType = propertyDescriptor.type;
  7660. if (sourceProperty !== undefined && sourceProperty !== null) {
  7661. switch (propertyType) {
  7662. case 0: // Value
  7663. case 6: // Mesh reference
  7664. case 11: // Camera reference
  7665. destination[property] = sourceProperty;
  7666. break;
  7667. case 1: // Texture
  7668. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7669. break;
  7670. case 2: // Color3
  7671. case 3: // FresnelParameters
  7672. case 4: // Vector2
  7673. case 5: // Vector3
  7674. case 7: // Color Curves
  7675. case 10: // Quaternion
  7676. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7677. break;
  7678. }
  7679. }
  7680. }
  7681. return destination;
  7682. };
  7683. function getDirectStore(target) {
  7684. var classKey = target.getClassName();
  7685. if (!__decoratorInitialStore[classKey]) {
  7686. __decoratorInitialStore[classKey] = {};
  7687. }
  7688. return __decoratorInitialStore[classKey];
  7689. }
  7690. /**
  7691. * Return the list of properties flagged as serializable
  7692. * @param target: host object
  7693. */
  7694. function getMergedStore(target) {
  7695. var classKey = target.getClassName();
  7696. if (__mergedStore[classKey]) {
  7697. return __mergedStore[classKey];
  7698. }
  7699. __mergedStore[classKey] = {};
  7700. var store = __mergedStore[classKey];
  7701. var currentTarget = target;
  7702. var currentKey = classKey;
  7703. while (currentKey) {
  7704. var initialStore = __decoratorInitialStore[currentKey];
  7705. for (var property in initialStore) {
  7706. store[property] = initialStore[property];
  7707. }
  7708. var parent_1 = void 0;
  7709. var done = false;
  7710. do {
  7711. parent_1 = Object.getPrototypeOf(currentTarget);
  7712. if (!parent_1.getClassName) {
  7713. done = true;
  7714. break;
  7715. }
  7716. if (parent_1.getClassName() !== currentKey) {
  7717. break;
  7718. }
  7719. currentTarget = parent_1;
  7720. } while (parent_1);
  7721. if (done) {
  7722. break;
  7723. }
  7724. currentKey = parent_1.getClassName();
  7725. currentTarget = parent_1;
  7726. }
  7727. return store;
  7728. }
  7729. function generateSerializableMember(type, sourceName) {
  7730. return function (target, propertyKey) {
  7731. var classStore = getDirectStore(target);
  7732. if (!classStore[propertyKey]) {
  7733. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7734. }
  7735. };
  7736. }
  7737. function generateExpandMember(setCallback, targetKey) {
  7738. if (targetKey === void 0) { targetKey = null; }
  7739. return function (target, propertyKey) {
  7740. var key = targetKey || ("_" + propertyKey);
  7741. Object.defineProperty(target, propertyKey, {
  7742. get: function () {
  7743. return this[key];
  7744. },
  7745. set: function (value) {
  7746. if (this[key] === value) {
  7747. return;
  7748. }
  7749. this[key] = value;
  7750. target[setCallback].apply(this);
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. };
  7756. }
  7757. function expandToProperty(callback, targetKey) {
  7758. if (targetKey === void 0) { targetKey = null; }
  7759. return generateExpandMember(callback, targetKey);
  7760. }
  7761. BABYLON.expandToProperty = expandToProperty;
  7762. function serialize(sourceName) {
  7763. return generateSerializableMember(0, sourceName); // value member
  7764. }
  7765. BABYLON.serialize = serialize;
  7766. function serializeAsTexture(sourceName) {
  7767. return generateSerializableMember(1, sourceName); // texture member
  7768. }
  7769. BABYLON.serializeAsTexture = serializeAsTexture;
  7770. function serializeAsColor3(sourceName) {
  7771. return generateSerializableMember(2, sourceName); // color3 member
  7772. }
  7773. BABYLON.serializeAsColor3 = serializeAsColor3;
  7774. function serializeAsFresnelParameters(sourceName) {
  7775. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7776. }
  7777. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7778. function serializeAsVector2(sourceName) {
  7779. return generateSerializableMember(4, sourceName); // vector2 member
  7780. }
  7781. BABYLON.serializeAsVector2 = serializeAsVector2;
  7782. function serializeAsVector3(sourceName) {
  7783. return generateSerializableMember(5, sourceName); // vector3 member
  7784. }
  7785. BABYLON.serializeAsVector3 = serializeAsVector3;
  7786. function serializeAsMeshReference(sourceName) {
  7787. return generateSerializableMember(6, sourceName); // mesh reference member
  7788. }
  7789. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7790. function serializeAsColorCurves(sourceName) {
  7791. return generateSerializableMember(7, sourceName); // color curves
  7792. }
  7793. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7794. function serializeAsColor4(sourceName) {
  7795. return generateSerializableMember(8, sourceName); // color 4
  7796. }
  7797. BABYLON.serializeAsColor4 = serializeAsColor4;
  7798. function serializeAsImageProcessingConfiguration(sourceName) {
  7799. return generateSerializableMember(9, sourceName); // image processing
  7800. }
  7801. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7802. function serializeAsQuaternion(sourceName) {
  7803. return generateSerializableMember(10, sourceName); // quaternion member
  7804. }
  7805. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7806. /**
  7807. * Decorator used to define property that can be serialized as reference to a camera
  7808. * @param sourceName defines the name of the property to decorate
  7809. */
  7810. function serializeAsCameraReference(sourceName) {
  7811. return generateSerializableMember(11, sourceName); // camera reference member
  7812. }
  7813. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7814. var SerializationHelper = /** @class */ (function () {
  7815. function SerializationHelper() {
  7816. }
  7817. SerializationHelper.Serialize = function (entity, serializationObject) {
  7818. if (!serializationObject) {
  7819. serializationObject = {};
  7820. }
  7821. // Tags
  7822. if (BABYLON.Tags) {
  7823. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7824. }
  7825. var serializedProperties = getMergedStore(entity);
  7826. // Properties
  7827. for (var property in serializedProperties) {
  7828. var propertyDescriptor = serializedProperties[property];
  7829. var targetPropertyName = propertyDescriptor.sourceName || property;
  7830. var propertyType = propertyDescriptor.type;
  7831. var sourceProperty = entity[property];
  7832. if (sourceProperty !== undefined && sourceProperty !== null) {
  7833. switch (propertyType) {
  7834. case 0: // Value
  7835. serializationObject[targetPropertyName] = sourceProperty;
  7836. break;
  7837. case 1: // Texture
  7838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7839. break;
  7840. case 2: // Color3
  7841. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7842. break;
  7843. case 3: // FresnelParameters
  7844. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7845. break;
  7846. case 4: // Vector2
  7847. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7848. break;
  7849. case 5: // Vector3
  7850. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7851. break;
  7852. case 6: // Mesh reference
  7853. serializationObject[targetPropertyName] = sourceProperty.id;
  7854. break;
  7855. case 7: // Color Curves
  7856. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7857. break;
  7858. case 8: // Color 4
  7859. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7860. break;
  7861. case 9: // Image Processing
  7862. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7863. break;
  7864. case 10: // Quaternion
  7865. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7866. break;
  7867. case 11: // Camera reference
  7868. serializationObject[targetPropertyName] = sourceProperty.id;
  7869. break;
  7870. }
  7871. }
  7872. }
  7873. return serializationObject;
  7874. };
  7875. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7876. if (rootUrl === void 0) { rootUrl = null; }
  7877. var destination = creationFunction();
  7878. if (!rootUrl) {
  7879. rootUrl = "";
  7880. }
  7881. // Tags
  7882. if (BABYLON.Tags) {
  7883. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7884. }
  7885. var classStore = getMergedStore(destination);
  7886. // Properties
  7887. for (var property in classStore) {
  7888. var propertyDescriptor = classStore[property];
  7889. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7890. var propertyType = propertyDescriptor.type;
  7891. if (sourceProperty !== undefined && sourceProperty !== null) {
  7892. var dest = destination;
  7893. switch (propertyType) {
  7894. case 0: // Value
  7895. dest[property] = sourceProperty;
  7896. break;
  7897. case 1: // Texture
  7898. if (scene) {
  7899. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7900. }
  7901. break;
  7902. case 2: // Color3
  7903. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7904. break;
  7905. case 3: // FresnelParameters
  7906. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7907. break;
  7908. case 4: // Vector2
  7909. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7910. break;
  7911. case 5: // Vector3
  7912. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7913. break;
  7914. case 6: // Mesh reference
  7915. if (scene) {
  7916. dest[property] = scene.getLastMeshByID(sourceProperty);
  7917. }
  7918. break;
  7919. case 7: // Color Curves
  7920. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7921. break;
  7922. case 8: // Color 4
  7923. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7924. break;
  7925. case 9: // Image Processing
  7926. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7927. break;
  7928. case 10: // Quaternion
  7929. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7930. break;
  7931. case 11: // Camera reference
  7932. if (scene) {
  7933. dest[property] = scene.getCameraByID(sourceProperty);
  7934. }
  7935. break;
  7936. }
  7937. }
  7938. }
  7939. return destination;
  7940. };
  7941. SerializationHelper.Clone = function (creationFunction, source) {
  7942. return _copySource(creationFunction, source, false);
  7943. };
  7944. SerializationHelper.Instanciate = function (creationFunction, source) {
  7945. return _copySource(creationFunction, source, true);
  7946. };
  7947. return SerializationHelper;
  7948. }());
  7949. BABYLON.SerializationHelper = SerializationHelper;
  7950. })(BABYLON || (BABYLON = {}));
  7951. //# sourceMappingURL=babylon.decorators.js.map
  7952. var BABYLON;
  7953. (function (BABYLON) {
  7954. /**
  7955. * Wrapper class for promise with external resolve and reject.
  7956. */
  7957. var Deferred = /** @class */ (function () {
  7958. /**
  7959. * Constructor for this deferred object.
  7960. */
  7961. function Deferred() {
  7962. var _this = this;
  7963. this.promise = new Promise(function (resolve, reject) {
  7964. _this._resolve = resolve;
  7965. _this._reject = reject;
  7966. });
  7967. }
  7968. Object.defineProperty(Deferred.prototype, "resolve", {
  7969. /**
  7970. * The resolve method of the promise associated with this deferred object.
  7971. */
  7972. get: function () {
  7973. return this._resolve;
  7974. },
  7975. enumerable: true,
  7976. configurable: true
  7977. });
  7978. Object.defineProperty(Deferred.prototype, "reject", {
  7979. /**
  7980. * The reject method of the promise associated with this deferred object.
  7981. */
  7982. get: function () {
  7983. return this._reject;
  7984. },
  7985. enumerable: true,
  7986. configurable: true
  7987. });
  7988. return Deferred;
  7989. }());
  7990. BABYLON.Deferred = Deferred;
  7991. })(BABYLON || (BABYLON = {}));
  7992. //# sourceMappingURL=babylon.deferred.js.map
  7993. var BABYLON;
  7994. (function (BABYLON) {
  7995. /**
  7996. * A class serves as a medium between the observable and its observers
  7997. */
  7998. var EventState = /** @class */ (function () {
  7999. /**
  8000. * Create a new EventState
  8001. * @param mask defines the mask associated with this state
  8002. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8003. * @param target defines the original target of the state
  8004. * @param currentTarget defines the current target of the state
  8005. */
  8006. function EventState(mask, skipNextObservers, target, currentTarget) {
  8007. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8008. this.initalize(mask, skipNextObservers, target, currentTarget);
  8009. }
  8010. /**
  8011. * Initialize the current event state
  8012. * @param mask defines the mask associated with this state
  8013. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8014. * @param target defines the original target of the state
  8015. * @param currentTarget defines the current target of the state
  8016. * @returns the current event state
  8017. */
  8018. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8019. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8020. this.mask = mask;
  8021. this.skipNextObservers = skipNextObservers;
  8022. this.target = target;
  8023. this.currentTarget = currentTarget;
  8024. return this;
  8025. };
  8026. return EventState;
  8027. }());
  8028. BABYLON.EventState = EventState;
  8029. /**
  8030. * Represent an Observer registered to a given Observable object.
  8031. */
  8032. var Observer = /** @class */ (function () {
  8033. /**
  8034. * Creates a new observer
  8035. * @param callback defines the callback to call when the observer is notified
  8036. * @param mask defines the mask of the observer (used to filter notifications)
  8037. * @param scope defines the current scope used to restore the JS context
  8038. */
  8039. function Observer(
  8040. /**
  8041. * Defines the callback to call when the observer is notified
  8042. */
  8043. callback,
  8044. /**
  8045. * Defines the mask of the observer (used to filter notifications)
  8046. */
  8047. mask,
  8048. /**
  8049. * Defines the current scope used to restore the JS context
  8050. */
  8051. scope) {
  8052. if (scope === void 0) { scope = null; }
  8053. this.callback = callback;
  8054. this.mask = mask;
  8055. this.scope = scope;
  8056. /** @hidden */
  8057. this._willBeUnregistered = false;
  8058. /**
  8059. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8060. */
  8061. this.unregisterOnNextCall = false;
  8062. }
  8063. return Observer;
  8064. }());
  8065. BABYLON.Observer = Observer;
  8066. /**
  8067. * Represent a list of observers registered to multiple Observables object.
  8068. */
  8069. var MultiObserver = /** @class */ (function () {
  8070. function MultiObserver() {
  8071. }
  8072. /**
  8073. * Release associated resources
  8074. */
  8075. MultiObserver.prototype.dispose = function () {
  8076. if (this._observers && this._observables) {
  8077. for (var index = 0; index < this._observers.length; index++) {
  8078. this._observables[index].remove(this._observers[index]);
  8079. }
  8080. }
  8081. this._observers = null;
  8082. this._observables = null;
  8083. };
  8084. /**
  8085. * Raise a callback when one of the observable will notify
  8086. * @param observables defines a list of observables to watch
  8087. * @param callback defines the callback to call on notification
  8088. * @param mask defines the mask used to filter notifications
  8089. * @param scope defines the current scope used to restore the JS context
  8090. * @returns the new MultiObserver
  8091. */
  8092. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8093. if (mask === void 0) { mask = -1; }
  8094. if (scope === void 0) { scope = null; }
  8095. var result = new MultiObserver();
  8096. result._observers = new Array();
  8097. result._observables = observables;
  8098. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8099. var observable = observables_1[_i];
  8100. var observer = observable.add(callback, mask, false, scope);
  8101. if (observer) {
  8102. result._observers.push(observer);
  8103. }
  8104. }
  8105. return result;
  8106. };
  8107. return MultiObserver;
  8108. }());
  8109. BABYLON.MultiObserver = MultiObserver;
  8110. /**
  8111. * The Observable class is a simple implementation of the Observable pattern.
  8112. *
  8113. * 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.
  8114. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8115. * 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).
  8116. * 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.
  8117. */
  8118. var Observable = /** @class */ (function () {
  8119. /**
  8120. * Creates a new observable
  8121. * @param onObserverAdded defines a callback to call when a new observer is added
  8122. */
  8123. function Observable(onObserverAdded) {
  8124. this._observers = new Array();
  8125. this._eventState = new EventState(0);
  8126. if (onObserverAdded) {
  8127. this._onObserverAdded = onObserverAdded;
  8128. }
  8129. }
  8130. /**
  8131. * Create a new Observer with the specified callback
  8132. * @param callback the callback that will be executed for that Observer
  8133. * @param mask the mask used to filter observers
  8134. * @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.
  8135. * @param scope optional scope for the callback to be called from
  8136. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8137. * @returns the new observer created for the callback
  8138. */
  8139. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8140. if (mask === void 0) { mask = -1; }
  8141. if (insertFirst === void 0) { insertFirst = false; }
  8142. if (scope === void 0) { scope = null; }
  8143. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8144. if (!callback) {
  8145. return null;
  8146. }
  8147. var observer = new Observer(callback, mask, scope);
  8148. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8149. if (insertFirst) {
  8150. this._observers.unshift(observer);
  8151. }
  8152. else {
  8153. this._observers.push(observer);
  8154. }
  8155. if (this._onObserverAdded) {
  8156. this._onObserverAdded(observer);
  8157. }
  8158. return observer;
  8159. };
  8160. /**
  8161. * Create a new Observer with the specified callback and unregisters after the next notification
  8162. * @param callback the callback that will be executed for that Observer
  8163. * @returns the new observer created for the callback
  8164. */
  8165. Observable.prototype.addOnce = function (callback) {
  8166. return this.add(callback, undefined, undefined, undefined, true);
  8167. };
  8168. /**
  8169. * Remove an Observer from the Observable object
  8170. * @param observer the instance of the Observer to remove
  8171. * @returns false if it doesn't belong to this Observable
  8172. */
  8173. Observable.prototype.remove = function (observer) {
  8174. if (!observer) {
  8175. return false;
  8176. }
  8177. var index = this._observers.indexOf(observer);
  8178. if (index !== -1) {
  8179. this._observers.splice(index, 1);
  8180. return true;
  8181. }
  8182. return false;
  8183. };
  8184. /**
  8185. * Remove a callback from the Observable object
  8186. * @param callback the callback to remove
  8187. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8188. * @returns false if it doesn't belong to this Observable
  8189. */
  8190. Observable.prototype.removeCallback = function (callback, scope) {
  8191. for (var index = 0; index < this._observers.length; index++) {
  8192. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8193. this._observers.splice(index, 1);
  8194. return true;
  8195. }
  8196. }
  8197. return false;
  8198. };
  8199. Observable.prototype._deferUnregister = function (observer) {
  8200. var _this = this;
  8201. observer.unregisterOnNextCall = false;
  8202. observer._willBeUnregistered = true;
  8203. BABYLON.Tools.SetImmediate(function () {
  8204. _this.remove(observer);
  8205. });
  8206. };
  8207. /**
  8208. * Notify all Observers by calling their respective callback with the given data
  8209. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8210. * @param eventData defines the data to send to all observers
  8211. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8212. * @param target defines the original target of the state
  8213. * @param currentTarget defines the current target of the state
  8214. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8215. */
  8216. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8217. if (mask === void 0) { mask = -1; }
  8218. if (!this._observers.length) {
  8219. return true;
  8220. }
  8221. var state = this._eventState;
  8222. state.mask = mask;
  8223. state.target = target;
  8224. state.currentTarget = currentTarget;
  8225. state.skipNextObservers = false;
  8226. state.lastReturnValue = eventData;
  8227. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8228. var obs = _a[_i];
  8229. if (obs._willBeUnregistered) {
  8230. continue;
  8231. }
  8232. if (obs.mask & mask) {
  8233. if (obs.scope) {
  8234. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8235. }
  8236. else {
  8237. state.lastReturnValue = obs.callback(eventData, state);
  8238. }
  8239. if (obs.unregisterOnNextCall) {
  8240. this._deferUnregister(obs);
  8241. }
  8242. }
  8243. if (state.skipNextObservers) {
  8244. return false;
  8245. }
  8246. }
  8247. return true;
  8248. };
  8249. /**
  8250. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8251. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8252. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8253. * and it is crucial that all callbacks will be executed.
  8254. * The order of the callbacks is kept, callbacks are not executed parallel.
  8255. *
  8256. * @param eventData The data to be sent to each callback
  8257. * @param mask is used to filter observers defaults to -1
  8258. * @param target defines the callback target (see EventState)
  8259. * @param currentTarget defines he current object in the bubbling phase
  8260. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8261. */
  8262. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8263. var _this = this;
  8264. if (mask === void 0) { mask = -1; }
  8265. // create an empty promise
  8266. var p = Promise.resolve(eventData);
  8267. // no observers? return this promise.
  8268. if (!this._observers.length) {
  8269. return p;
  8270. }
  8271. var state = this._eventState;
  8272. state.mask = mask;
  8273. state.target = target;
  8274. state.currentTarget = currentTarget;
  8275. state.skipNextObservers = false;
  8276. // execute one callback after another (not using Promise.all, the order is important)
  8277. this._observers.forEach(function (obs) {
  8278. if (state.skipNextObservers) {
  8279. return;
  8280. }
  8281. if (obs._willBeUnregistered) {
  8282. return;
  8283. }
  8284. if (obs.mask & mask) {
  8285. if (obs.scope) {
  8286. p = p.then(function (lastReturnedValue) {
  8287. state.lastReturnValue = lastReturnedValue;
  8288. return obs.callback.apply(obs.scope, [eventData, state]);
  8289. });
  8290. }
  8291. else {
  8292. p = p.then(function (lastReturnedValue) {
  8293. state.lastReturnValue = lastReturnedValue;
  8294. return obs.callback(eventData, state);
  8295. });
  8296. }
  8297. if (obs.unregisterOnNextCall) {
  8298. _this._deferUnregister(obs);
  8299. }
  8300. }
  8301. });
  8302. // return the eventData
  8303. return p.then(function () { return eventData; });
  8304. };
  8305. /**
  8306. * Notify a specific observer
  8307. * @param observer defines the observer to notify
  8308. * @param eventData defines the data to be sent to each callback
  8309. * @param mask is used to filter observers defaults to -1
  8310. */
  8311. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8312. if (mask === void 0) { mask = -1; }
  8313. var state = this._eventState;
  8314. state.mask = mask;
  8315. state.skipNextObservers = false;
  8316. observer.callback(eventData, state);
  8317. };
  8318. /**
  8319. * Gets a boolean indicating if the observable has at least one observer
  8320. * @returns true is the Observable has at least one Observer registered
  8321. */
  8322. Observable.prototype.hasObservers = function () {
  8323. return this._observers.length > 0;
  8324. };
  8325. /**
  8326. * Clear the list of observers
  8327. */
  8328. Observable.prototype.clear = function () {
  8329. this._observers = new Array();
  8330. this._onObserverAdded = null;
  8331. };
  8332. /**
  8333. * Clone the current observable
  8334. * @returns a new observable
  8335. */
  8336. Observable.prototype.clone = function () {
  8337. var result = new Observable();
  8338. result._observers = this._observers.slice(0);
  8339. return result;
  8340. };
  8341. /**
  8342. * Does this observable handles observer registered with a given mask
  8343. * @param mask defines the mask to be tested
  8344. * @return whether or not one observer registered with the given mask is handeled
  8345. **/
  8346. Observable.prototype.hasSpecificMask = function (mask) {
  8347. if (mask === void 0) { mask = -1; }
  8348. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8349. var obs = _a[_i];
  8350. if (obs.mask & mask || obs.mask === mask) {
  8351. return true;
  8352. }
  8353. }
  8354. return false;
  8355. };
  8356. return Observable;
  8357. }());
  8358. BABYLON.Observable = Observable;
  8359. })(BABYLON || (BABYLON = {}));
  8360. //# sourceMappingURL=babylon.observable.js.map
  8361. var BABYLON;
  8362. (function (BABYLON) {
  8363. var SmartArray = /** @class */ (function () {
  8364. function SmartArray(capacity) {
  8365. this.length = 0;
  8366. this.data = new Array(capacity);
  8367. this._id = SmartArray._GlobalId++;
  8368. }
  8369. SmartArray.prototype.push = function (value) {
  8370. this.data[this.length++] = value;
  8371. if (this.length > this.data.length) {
  8372. this.data.length *= 2;
  8373. }
  8374. };
  8375. SmartArray.prototype.forEach = function (func) {
  8376. for (var index = 0; index < this.length; index++) {
  8377. func(this.data[index]);
  8378. }
  8379. };
  8380. SmartArray.prototype.sort = function (compareFn) {
  8381. this.data.sort(compareFn);
  8382. };
  8383. SmartArray.prototype.reset = function () {
  8384. this.length = 0;
  8385. };
  8386. SmartArray.prototype.dispose = function () {
  8387. this.reset();
  8388. if (this.data) {
  8389. this.data.length = 0;
  8390. this.data = [];
  8391. }
  8392. };
  8393. SmartArray.prototype.concat = function (array) {
  8394. if (array.length === 0) {
  8395. return;
  8396. }
  8397. if (this.length + array.length > this.data.length) {
  8398. this.data.length = (this.length + array.length) * 2;
  8399. }
  8400. for (var index = 0; index < array.length; index++) {
  8401. this.data[this.length++] = (array.data || array)[index];
  8402. }
  8403. };
  8404. SmartArray.prototype.indexOf = function (value) {
  8405. var position = this.data.indexOf(value);
  8406. if (position >= this.length) {
  8407. return -1;
  8408. }
  8409. return position;
  8410. };
  8411. SmartArray.prototype.contains = function (value) {
  8412. return this.data.indexOf(value) !== -1;
  8413. };
  8414. // Statics
  8415. SmartArray._GlobalId = 0;
  8416. return SmartArray;
  8417. }());
  8418. BABYLON.SmartArray = SmartArray;
  8419. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8420. __extends(SmartArrayNoDuplicate, _super);
  8421. function SmartArrayNoDuplicate() {
  8422. var _this = _super !== null && _super.apply(this, arguments) || this;
  8423. _this._duplicateId = 0;
  8424. return _this;
  8425. }
  8426. SmartArrayNoDuplicate.prototype.push = function (value) {
  8427. _super.prototype.push.call(this, value);
  8428. if (!value.__smartArrayFlags) {
  8429. value.__smartArrayFlags = {};
  8430. }
  8431. value.__smartArrayFlags[this._id] = this._duplicateId;
  8432. };
  8433. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8434. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8435. return false;
  8436. }
  8437. this.push(value);
  8438. return true;
  8439. };
  8440. SmartArrayNoDuplicate.prototype.reset = function () {
  8441. _super.prototype.reset.call(this);
  8442. this._duplicateId++;
  8443. };
  8444. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8445. if (array.length === 0) {
  8446. return;
  8447. }
  8448. if (this.length + array.length > this.data.length) {
  8449. this.data.length = (this.length + array.length) * 2;
  8450. }
  8451. for (var index = 0; index < array.length; index++) {
  8452. var item = (array.data || array)[index];
  8453. this.pushNoDuplicate(item);
  8454. }
  8455. };
  8456. return SmartArrayNoDuplicate;
  8457. }(SmartArray));
  8458. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8459. })(BABYLON || (BABYLON = {}));
  8460. //# sourceMappingURL=babylon.smartArray.js.map
  8461. var BABYLON;
  8462. (function (BABYLON) {
  8463. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8464. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8465. var LoadFileError = /** @class */ (function (_super) {
  8466. __extends(LoadFileError, _super);
  8467. function LoadFileError(message, request) {
  8468. var _this = _super.call(this, message) || this;
  8469. _this.request = request;
  8470. _this.name = "LoadFileError";
  8471. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8472. return _this;
  8473. }
  8474. // Polyfill for Object.setPrototypeOf if necessary.
  8475. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8476. return LoadFileError;
  8477. }(Error));
  8478. BABYLON.LoadFileError = LoadFileError;
  8479. var RetryStrategy = /** @class */ (function () {
  8480. function RetryStrategy() {
  8481. }
  8482. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8483. if (maxRetries === void 0) { maxRetries = 3; }
  8484. if (baseInterval === void 0) { baseInterval = 500; }
  8485. return function (url, request, retryIndex) {
  8486. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8487. return -1;
  8488. }
  8489. return Math.pow(2, retryIndex) * baseInterval;
  8490. };
  8491. };
  8492. return RetryStrategy;
  8493. }());
  8494. BABYLON.RetryStrategy = RetryStrategy;
  8495. // Screenshots
  8496. var screenshotCanvas;
  8497. var cloneValue = function (source, destinationObject) {
  8498. if (!source)
  8499. return null;
  8500. if (source instanceof BABYLON.Mesh) {
  8501. return null;
  8502. }
  8503. if (source instanceof BABYLON.SubMesh) {
  8504. return source.clone(destinationObject);
  8505. }
  8506. else if (source.clone) {
  8507. return source.clone();
  8508. }
  8509. return null;
  8510. };
  8511. var Tools = /** @class */ (function () {
  8512. function Tools() {
  8513. }
  8514. /**
  8515. * Interpolates between a and b via alpha
  8516. * @param a The lower value (returned when alpha = 0)
  8517. * @param b The upper value (returned when alpha = 1)
  8518. * @param alpha The interpolation-factor
  8519. * @return The mixed value
  8520. */
  8521. Tools.Mix = function (a, b, alpha) {
  8522. return a * (1 - alpha) + b * alpha;
  8523. };
  8524. Tools.Instantiate = function (className) {
  8525. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8526. return Tools.RegisteredExternalClasses[className];
  8527. }
  8528. var arr = className.split(".");
  8529. var fn = (window || this);
  8530. for (var i = 0, len = arr.length; i < len; i++) {
  8531. fn = fn[arr[i]];
  8532. }
  8533. if (typeof fn !== "function") {
  8534. return null;
  8535. }
  8536. return fn;
  8537. };
  8538. /**
  8539. * Provides a slice function that will work even on IE
  8540. * @param data defines the array to slice
  8541. * @param start defines the start of the data (optional)
  8542. * @param end defines the end of the data (optional)
  8543. * @returns the new sliced array
  8544. */
  8545. Tools.Slice = function (data, start, end) {
  8546. if (data.slice) {
  8547. return data.slice(start, end);
  8548. }
  8549. return Array.prototype.slice.call(data, start, end);
  8550. };
  8551. Tools.SetImmediate = function (action) {
  8552. if (window.setImmediate) {
  8553. window.setImmediate(action);
  8554. }
  8555. else {
  8556. setTimeout(action, 1);
  8557. }
  8558. };
  8559. Tools.IsExponentOfTwo = function (value) {
  8560. var count = 1;
  8561. do {
  8562. count *= 2;
  8563. } while (count < value);
  8564. return count === value;
  8565. };
  8566. /**
  8567. * Returns the nearest 32-bit single precision float representation of a Number
  8568. * @param value A Number. If the parameter is of a different type, it will get converted
  8569. * to a number or to NaN if it cannot be converted
  8570. * @returns number
  8571. */
  8572. Tools.FloatRound = function (value) {
  8573. if (Math.fround) {
  8574. return Math.fround(value);
  8575. }
  8576. return (Tools._tmpFloatArray[0] = value);
  8577. };
  8578. /**
  8579. * Find the next highest power of two.
  8580. * @param x Number to start search from.
  8581. * @return Next highest power of two.
  8582. */
  8583. Tools.CeilingPOT = function (x) {
  8584. x--;
  8585. x |= x >> 1;
  8586. x |= x >> 2;
  8587. x |= x >> 4;
  8588. x |= x >> 8;
  8589. x |= x >> 16;
  8590. x++;
  8591. return x;
  8592. };
  8593. /**
  8594. * Find the next lowest power of two.
  8595. * @param x Number to start search from.
  8596. * @return Next lowest power of two.
  8597. */
  8598. Tools.FloorPOT = function (x) {
  8599. x = x | (x >> 1);
  8600. x = x | (x >> 2);
  8601. x = x | (x >> 4);
  8602. x = x | (x >> 8);
  8603. x = x | (x >> 16);
  8604. return x - (x >> 1);
  8605. };
  8606. /**
  8607. * Find the nearest power of two.
  8608. * @param x Number to start search from.
  8609. * @return Next nearest power of two.
  8610. */
  8611. Tools.NearestPOT = function (x) {
  8612. var c = Tools.CeilingPOT(x);
  8613. var f = Tools.FloorPOT(x);
  8614. return (c - x) > (x - f) ? f : c;
  8615. };
  8616. Tools.GetExponentOfTwo = function (value, max, mode) {
  8617. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8618. var pot;
  8619. switch (mode) {
  8620. case BABYLON.Engine.SCALEMODE_FLOOR:
  8621. pot = Tools.FloorPOT(value);
  8622. break;
  8623. case BABYLON.Engine.SCALEMODE_NEAREST:
  8624. pot = Tools.NearestPOT(value);
  8625. break;
  8626. case BABYLON.Engine.SCALEMODE_CEILING:
  8627. default:
  8628. pot = Tools.CeilingPOT(value);
  8629. break;
  8630. }
  8631. return Math.min(pot, max);
  8632. };
  8633. Tools.GetFilename = function (path) {
  8634. var index = path.lastIndexOf("/");
  8635. if (index < 0)
  8636. return path;
  8637. return path.substring(index + 1);
  8638. };
  8639. /**
  8640. * Extracts the "folder" part of a path (everything before the filename).
  8641. * @param uri The URI to extract the info from
  8642. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8643. * @returns The "folder" part of the path
  8644. */
  8645. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8646. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8647. var index = uri.lastIndexOf("/");
  8648. if (index < 0) {
  8649. if (returnUnchangedIfNoSlash) {
  8650. return uri;
  8651. }
  8652. return "";
  8653. }
  8654. return uri.substring(0, index + 1);
  8655. };
  8656. Tools.GetDOMTextContent = function (element) {
  8657. var result = "";
  8658. var child = element.firstChild;
  8659. while (child) {
  8660. if (child.nodeType === 3) {
  8661. result += child.textContent;
  8662. }
  8663. child = child.nextSibling;
  8664. }
  8665. return result;
  8666. };
  8667. Tools.ToDegrees = function (angle) {
  8668. return angle * 180 / Math.PI;
  8669. };
  8670. Tools.ToRadians = function (angle) {
  8671. return angle * Math.PI / 180;
  8672. };
  8673. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8674. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8675. var output = "";
  8676. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8677. var i = 0;
  8678. var bytes = new Uint8Array(buffer);
  8679. while (i < bytes.length) {
  8680. chr1 = bytes[i++];
  8681. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8682. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8683. enc1 = chr1 >> 2;
  8684. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8685. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8686. enc4 = chr3 & 63;
  8687. if (isNaN(chr2)) {
  8688. enc3 = enc4 = 64;
  8689. }
  8690. else if (isNaN(chr3)) {
  8691. enc4 = 64;
  8692. }
  8693. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8694. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8695. }
  8696. return "data:image/png;base64," + output;
  8697. };
  8698. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8699. if (bias === void 0) { bias = null; }
  8700. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8701. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8702. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8703. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8704. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8705. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8706. }
  8707. if (bias) {
  8708. minimum.x -= minimum.x * bias.x + bias.y;
  8709. minimum.y -= minimum.y * bias.x + bias.y;
  8710. minimum.z -= minimum.z * bias.x + bias.y;
  8711. maximum.x += maximum.x * bias.x + bias.y;
  8712. maximum.y += maximum.y * bias.x + bias.y;
  8713. maximum.z += maximum.z * bias.x + bias.y;
  8714. }
  8715. return {
  8716. minimum: minimum,
  8717. maximum: maximum
  8718. };
  8719. };
  8720. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8721. if (bias === void 0) { bias = null; }
  8722. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8723. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8724. if (!stride) {
  8725. stride = 3;
  8726. }
  8727. for (var index = start; index < start + count; index++) {
  8728. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8729. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8730. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8731. }
  8732. if (bias) {
  8733. minimum.x -= minimum.x * bias.x + bias.y;
  8734. minimum.y -= minimum.y * bias.x + bias.y;
  8735. minimum.z -= minimum.z * bias.x + bias.y;
  8736. maximum.x += maximum.x * bias.x + bias.y;
  8737. maximum.y += maximum.y * bias.x + bias.y;
  8738. maximum.z += maximum.z * bias.x + bias.y;
  8739. }
  8740. return {
  8741. minimum: minimum,
  8742. maximum: maximum
  8743. };
  8744. };
  8745. Tools.Vector2ArrayFeeder = function (array) {
  8746. return function (index) {
  8747. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8748. var length = isFloatArray ? array.length / 2 : array.length;
  8749. if (index >= length) {
  8750. return null;
  8751. }
  8752. if (isFloatArray) {
  8753. var fa = array;
  8754. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8755. }
  8756. var a = array;
  8757. return a[index];
  8758. };
  8759. };
  8760. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8761. if (bias === void 0) { bias = null; }
  8762. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8763. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8764. var i = 0;
  8765. var cur = feeder(i++);
  8766. while (cur) {
  8767. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8768. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8769. cur = feeder(i++);
  8770. }
  8771. if (bias) {
  8772. minimum.x -= minimum.x * bias.x + bias.y;
  8773. minimum.y -= minimum.y * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. }
  8777. return {
  8778. minimum: minimum,
  8779. maximum: maximum
  8780. };
  8781. };
  8782. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8783. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8784. return null;
  8785. return Array.isArray(obj) ? obj : [obj];
  8786. };
  8787. // Misc.
  8788. Tools.GetPointerPrefix = function () {
  8789. var eventPrefix = "pointer";
  8790. // Check if pointer events are supported
  8791. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8792. eventPrefix = "mouse";
  8793. }
  8794. return eventPrefix;
  8795. };
  8796. /**
  8797. * @param func - the function to be called
  8798. * @param requester - the object that will request the next frame. Falls back to window.
  8799. */
  8800. Tools.QueueNewFrame = function (func, requester) {
  8801. if (!Tools.IsWindowObjectExist()) {
  8802. return setTimeout(func, 16);
  8803. }
  8804. if (!requester) {
  8805. requester = window;
  8806. }
  8807. if (requester.requestAnimationFrame) {
  8808. return requester.requestAnimationFrame(func);
  8809. }
  8810. else if (requester.msRequestAnimationFrame) {
  8811. return requester.msRequestAnimationFrame(func);
  8812. }
  8813. else if (requester.webkitRequestAnimationFrame) {
  8814. return requester.webkitRequestAnimationFrame(func);
  8815. }
  8816. else if (requester.mozRequestAnimationFrame) {
  8817. return requester.mozRequestAnimationFrame(func);
  8818. }
  8819. else if (requester.oRequestAnimationFrame) {
  8820. return requester.oRequestAnimationFrame(func);
  8821. }
  8822. else {
  8823. return window.setTimeout(func, 16);
  8824. }
  8825. };
  8826. Tools.RequestFullscreen = function (element) {
  8827. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8828. if (!requestFunction)
  8829. return;
  8830. requestFunction.call(element);
  8831. };
  8832. Tools.ExitFullscreen = function () {
  8833. if (document.exitFullscreen) {
  8834. document.exitFullscreen();
  8835. }
  8836. else if (document.mozCancelFullScreen) {
  8837. document.mozCancelFullScreen();
  8838. }
  8839. else if (document.webkitCancelFullScreen) {
  8840. document.webkitCancelFullScreen();
  8841. }
  8842. else if (document.msCancelFullScreen) {
  8843. document.msCancelFullScreen();
  8844. }
  8845. };
  8846. Tools.SetCorsBehavior = function (url, element) {
  8847. if (url && url.indexOf("data:") === 0) {
  8848. return;
  8849. }
  8850. if (Tools.CorsBehavior) {
  8851. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8852. element.crossOrigin = Tools.CorsBehavior;
  8853. }
  8854. else {
  8855. var result = Tools.CorsBehavior(url);
  8856. if (result) {
  8857. element.crossOrigin = result;
  8858. }
  8859. }
  8860. }
  8861. };
  8862. // External files
  8863. Tools.CleanUrl = function (url) {
  8864. url = url.replace(/#/mg, "%23");
  8865. return url;
  8866. };
  8867. /**
  8868. * Loads an image as an HTMLImageElement.
  8869. * @param input url string, ArrayBuffer, or Blob to load
  8870. * @param onLoad callback called when the image successfully loads
  8871. * @param onError callback called when the image fails to load
  8872. * @param database database for caching
  8873. * @returns the HTMLImageElement of the loaded image
  8874. */
  8875. Tools.LoadImage = function (input, onLoad, onError, database) {
  8876. var url;
  8877. var usingObjectURL = false;
  8878. if (input instanceof ArrayBuffer) {
  8879. url = URL.createObjectURL(new Blob([input]));
  8880. usingObjectURL = true;
  8881. }
  8882. else if (input instanceof Blob) {
  8883. url = URL.createObjectURL(input);
  8884. usingObjectURL = true;
  8885. }
  8886. else {
  8887. url = Tools.CleanUrl(input);
  8888. url = Tools.PreprocessUrl(input);
  8889. }
  8890. var img = new Image();
  8891. Tools.SetCorsBehavior(url, img);
  8892. var loadHandler = function () {
  8893. if (usingObjectURL && img.src) {
  8894. URL.revokeObjectURL(img.src);
  8895. }
  8896. img.removeEventListener("load", loadHandler);
  8897. img.removeEventListener("error", errorHandler);
  8898. onLoad(img);
  8899. };
  8900. var errorHandler = function (err) {
  8901. if (usingObjectURL && img.src) {
  8902. URL.revokeObjectURL(img.src);
  8903. }
  8904. img.removeEventListener("load", loadHandler);
  8905. img.removeEventListener("error", errorHandler);
  8906. Tools.Error("Error while trying to load image: " + input);
  8907. if (onError) {
  8908. onError("Error while trying to load image: " + input, err);
  8909. }
  8910. };
  8911. img.addEventListener("load", loadHandler);
  8912. img.addEventListener("error", errorHandler);
  8913. var noIndexedDB = function () {
  8914. img.src = url;
  8915. };
  8916. var loadFromIndexedDB = function () {
  8917. if (database) {
  8918. database.loadImageFromDB(url, img);
  8919. }
  8920. };
  8921. //ANY database to do!
  8922. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8923. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8924. }
  8925. else {
  8926. if (url.indexOf("file:") !== -1) {
  8927. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8928. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8929. try {
  8930. var blobURL;
  8931. try {
  8932. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8933. }
  8934. catch (ex) {
  8935. // Chrome doesn't support oneTimeOnly parameter
  8936. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8937. }
  8938. img.src = blobURL;
  8939. usingObjectURL = true;
  8940. }
  8941. catch (e) {
  8942. img.src = "";
  8943. }
  8944. return img;
  8945. }
  8946. }
  8947. noIndexedDB();
  8948. }
  8949. return img;
  8950. };
  8951. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8952. url = Tools.CleanUrl(url);
  8953. url = Tools.PreprocessUrl(url);
  8954. // If file and file input are set
  8955. if (url.indexOf("file:") !== -1) {
  8956. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8957. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8958. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8959. }
  8960. }
  8961. var loadUrl = Tools.BaseUrl + url;
  8962. var aborted = false;
  8963. var fileRequest = {
  8964. onCompleteObservable: new BABYLON.Observable(),
  8965. abort: function () { return aborted = true; },
  8966. };
  8967. var requestFile = function () {
  8968. var request = new XMLHttpRequest();
  8969. var retryHandle = null;
  8970. fileRequest.abort = function () {
  8971. aborted = true;
  8972. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8973. request.abort();
  8974. }
  8975. if (retryHandle !== null) {
  8976. clearTimeout(retryHandle);
  8977. retryHandle = null;
  8978. }
  8979. };
  8980. var retryLoop = function (retryIndex) {
  8981. request.open('GET', loadUrl, true);
  8982. if (useArrayBuffer) {
  8983. request.responseType = "arraybuffer";
  8984. }
  8985. if (onProgress) {
  8986. request.addEventListener("progress", onProgress);
  8987. }
  8988. var onLoadEnd = function () {
  8989. request.removeEventListener("loadend", onLoadEnd);
  8990. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8991. fileRequest.onCompleteObservable.clear();
  8992. };
  8993. request.addEventListener("loadend", onLoadEnd);
  8994. var onReadyStateChange = function () {
  8995. if (aborted) {
  8996. return;
  8997. }
  8998. // In case of undefined state in some browsers.
  8999. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9000. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9001. request.removeEventListener("readystatechange", onReadyStateChange);
  9002. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9003. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9004. return;
  9005. }
  9006. var retryStrategy = Tools.DefaultRetryStrategy;
  9007. if (retryStrategy) {
  9008. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9009. if (waitTime !== -1) {
  9010. // Prevent the request from completing for retry.
  9011. request.removeEventListener("loadend", onLoadEnd);
  9012. request = new XMLHttpRequest();
  9013. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9014. return;
  9015. }
  9016. }
  9017. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9018. if (onError) {
  9019. onError(request, e);
  9020. }
  9021. else {
  9022. throw e;
  9023. }
  9024. }
  9025. };
  9026. request.addEventListener("readystatechange", onReadyStateChange);
  9027. request.send();
  9028. };
  9029. retryLoop(0);
  9030. };
  9031. // Caching all files
  9032. if (database && database.enableSceneOffline) {
  9033. var noIndexedDB_1 = function () {
  9034. if (!aborted) {
  9035. requestFile();
  9036. }
  9037. };
  9038. var loadFromIndexedDB = function () {
  9039. // TODO: database needs to support aborting and should return a IFileRequest
  9040. if (aborted) {
  9041. return;
  9042. }
  9043. if (database) {
  9044. database.loadFileFromDB(url, function (data) {
  9045. if (!aborted) {
  9046. onSuccess(data);
  9047. }
  9048. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9049. }, onProgress ? function (event) {
  9050. if (!aborted) {
  9051. onProgress(event);
  9052. }
  9053. } : undefined, noIndexedDB_1, useArrayBuffer);
  9054. }
  9055. };
  9056. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9057. }
  9058. else {
  9059. requestFile();
  9060. }
  9061. return fileRequest;
  9062. };
  9063. /**
  9064. * Load a script (identified by an url). When the url returns, the
  9065. * content of this file is added into a new script element, attached to the DOM (body element)
  9066. */
  9067. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9068. var head = document.getElementsByTagName('head')[0];
  9069. var script = document.createElement('script');
  9070. script.type = 'text/javascript';
  9071. script.src = scriptUrl;
  9072. script.onload = function () {
  9073. if (onSuccess) {
  9074. onSuccess();
  9075. }
  9076. };
  9077. script.onerror = function (e) {
  9078. if (onError) {
  9079. onError("Unable to load script '" + scriptUrl + "'", e);
  9080. }
  9081. };
  9082. head.appendChild(script);
  9083. };
  9084. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9085. var reader = new FileReader();
  9086. var request = {
  9087. onCompleteObservable: new BABYLON.Observable(),
  9088. abort: function () { return reader.abort(); },
  9089. };
  9090. reader.onloadend = function (e) {
  9091. request.onCompleteObservable.notifyObservers(request);
  9092. };
  9093. reader.onload = function (e) {
  9094. //target doesn't have result from ts 1.3
  9095. callback(e.target['result']);
  9096. };
  9097. reader.onprogress = progressCallback;
  9098. reader.readAsDataURL(fileToLoad);
  9099. return request;
  9100. };
  9101. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9102. var reader = new FileReader();
  9103. var request = {
  9104. onCompleteObservable: new BABYLON.Observable(),
  9105. abort: function () { return reader.abort(); },
  9106. };
  9107. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9108. reader.onerror = function (e) {
  9109. Tools.Log("Error while reading file: " + fileToLoad.name);
  9110. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9111. };
  9112. reader.onload = function (e) {
  9113. //target doesn't have result from ts 1.3
  9114. callback(e.target['result']);
  9115. };
  9116. if (progressCallBack) {
  9117. reader.onprogress = progressCallBack;
  9118. }
  9119. if (!useArrayBuffer) {
  9120. // Asynchronous read
  9121. reader.readAsText(fileToLoad);
  9122. }
  9123. else {
  9124. reader.readAsArrayBuffer(fileToLoad);
  9125. }
  9126. return request;
  9127. };
  9128. //returns a downloadable url to a file content.
  9129. Tools.FileAsURL = function (content) {
  9130. var fileBlob = new Blob([content]);
  9131. var url = window.URL || window.webkitURL;
  9132. var link = url.createObjectURL(fileBlob);
  9133. return link;
  9134. };
  9135. // Misc.
  9136. Tools.Format = function (value, decimals) {
  9137. if (decimals === void 0) { decimals = 2; }
  9138. return value.toFixed(decimals);
  9139. };
  9140. Tools.CheckExtends = function (v, min, max) {
  9141. if (v.x < min.x)
  9142. min.x = v.x;
  9143. if (v.y < min.y)
  9144. min.y = v.y;
  9145. if (v.z < min.z)
  9146. min.z = v.z;
  9147. if (v.x > max.x)
  9148. max.x = v.x;
  9149. if (v.y > max.y)
  9150. max.y = v.y;
  9151. if (v.z > max.z)
  9152. max.z = v.z;
  9153. };
  9154. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9155. for (var prop in source) {
  9156. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9157. continue;
  9158. }
  9159. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9160. continue;
  9161. }
  9162. var sourceValue = source[prop];
  9163. var typeOfSourceValue = typeof sourceValue;
  9164. if (typeOfSourceValue === "function") {
  9165. continue;
  9166. }
  9167. try {
  9168. if (typeOfSourceValue === "object") {
  9169. if (sourceValue instanceof Array) {
  9170. destination[prop] = [];
  9171. if (sourceValue.length > 0) {
  9172. if (typeof sourceValue[0] == "object") {
  9173. for (var index = 0; index < sourceValue.length; index++) {
  9174. var clonedValue = cloneValue(sourceValue[index], destination);
  9175. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9176. destination[prop].push(clonedValue);
  9177. }
  9178. }
  9179. }
  9180. else {
  9181. destination[prop] = sourceValue.slice(0);
  9182. }
  9183. }
  9184. }
  9185. else {
  9186. destination[prop] = cloneValue(sourceValue, destination);
  9187. }
  9188. }
  9189. else {
  9190. destination[prop] = sourceValue;
  9191. }
  9192. }
  9193. catch (e) {
  9194. // Just ignore error (it could be because of a read-only property)
  9195. }
  9196. }
  9197. };
  9198. Tools.IsEmpty = function (obj) {
  9199. for (var i in obj) {
  9200. if (obj.hasOwnProperty(i)) {
  9201. return false;
  9202. }
  9203. }
  9204. return true;
  9205. };
  9206. Tools.RegisterTopRootEvents = function (events) {
  9207. for (var index = 0; index < events.length; index++) {
  9208. var event = events[index];
  9209. window.addEventListener(event.name, event.handler, false);
  9210. try {
  9211. if (window.parent) {
  9212. window.parent.addEventListener(event.name, event.handler, false);
  9213. }
  9214. }
  9215. catch (e) {
  9216. // Silently fails...
  9217. }
  9218. }
  9219. };
  9220. Tools.UnregisterTopRootEvents = function (events) {
  9221. for (var index = 0; index < events.length; index++) {
  9222. var event = events[index];
  9223. window.removeEventListener(event.name, event.handler);
  9224. try {
  9225. if (window.parent) {
  9226. window.parent.removeEventListener(event.name, event.handler);
  9227. }
  9228. }
  9229. catch (e) {
  9230. // Silently fails...
  9231. }
  9232. }
  9233. };
  9234. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9235. if (mimeType === void 0) { mimeType = "image/png"; }
  9236. // Read the contents of the framebuffer
  9237. var numberOfChannelsByLine = width * 4;
  9238. var halfHeight = height / 2;
  9239. //Reading datas from WebGL
  9240. var data = engine.readPixels(0, 0, width, height);
  9241. //To flip image on Y axis.
  9242. for (var i = 0; i < halfHeight; i++) {
  9243. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9244. var currentCell = j + i * numberOfChannelsByLine;
  9245. var targetLine = height - i - 1;
  9246. var targetCell = j + targetLine * numberOfChannelsByLine;
  9247. var temp = data[currentCell];
  9248. data[currentCell] = data[targetCell];
  9249. data[targetCell] = temp;
  9250. }
  9251. }
  9252. // Create a 2D canvas to store the result
  9253. if (!screenshotCanvas) {
  9254. screenshotCanvas = document.createElement('canvas');
  9255. }
  9256. screenshotCanvas.width = width;
  9257. screenshotCanvas.height = height;
  9258. var context = screenshotCanvas.getContext('2d');
  9259. if (context) {
  9260. // Copy the pixels to a 2D canvas
  9261. var imageData = context.createImageData(width, height);
  9262. var castData = (imageData.data);
  9263. castData.set(data);
  9264. context.putImageData(imageData, 0, 0);
  9265. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9266. }
  9267. };
  9268. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9269. if (mimeType === void 0) { mimeType = "image/png"; }
  9270. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9271. if (successCallback) {
  9272. successCallback(base64Image);
  9273. }
  9274. else {
  9275. // We need HTMLCanvasElement.toBlob for HD screenshots
  9276. if (!screenshotCanvas.toBlob) {
  9277. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9278. screenshotCanvas.toBlob = function (callback, type, quality) {
  9279. var _this = this;
  9280. setTimeout(function () {
  9281. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9282. for (var i = 0; i < len; i++) {
  9283. arr[i] = binStr.charCodeAt(i);
  9284. }
  9285. callback(new Blob([arr], { type: type || 'image/png' }));
  9286. });
  9287. };
  9288. }
  9289. screenshotCanvas.toBlob(function (blob) {
  9290. var url = URL.createObjectURL(blob);
  9291. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9292. if (("download" in document.createElement("a"))) {
  9293. var a = window.document.createElement("a");
  9294. a.href = url;
  9295. if (fileName) {
  9296. a.setAttribute("download", fileName);
  9297. }
  9298. else {
  9299. var date = new Date();
  9300. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9301. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9302. }
  9303. window.document.body.appendChild(a);
  9304. a.addEventListener("click", function () {
  9305. if (a.parentElement) {
  9306. a.parentElement.removeChild(a);
  9307. }
  9308. });
  9309. a.click();
  9310. }
  9311. else {
  9312. var newWindow = window.open("");
  9313. if (!newWindow)
  9314. return;
  9315. var img = newWindow.document.createElement("img");
  9316. img.onload = function () {
  9317. // no longer need to read the blob so it's revoked
  9318. URL.revokeObjectURL(url);
  9319. };
  9320. img.src = url;
  9321. newWindow.document.body.appendChild(img);
  9322. }
  9323. });
  9324. }
  9325. };
  9326. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9327. if (mimeType === void 0) { mimeType = "image/png"; }
  9328. var width;
  9329. var height;
  9330. // If a precision value is specified
  9331. if (size.precision) {
  9332. width = Math.round(engine.getRenderWidth() * size.precision);
  9333. height = Math.round(width / engine.getAspectRatio(camera));
  9334. }
  9335. else if (size.width && size.height) {
  9336. width = size.width;
  9337. height = size.height;
  9338. }
  9339. //If passing only width, computing height to keep display canvas ratio.
  9340. else if (size.width && !size.height) {
  9341. width = size.width;
  9342. height = Math.round(width / engine.getAspectRatio(camera));
  9343. }
  9344. //If passing only height, computing width to keep display canvas ratio.
  9345. else if (size.height && !size.width) {
  9346. height = size.height;
  9347. width = Math.round(height * engine.getAspectRatio(camera));
  9348. }
  9349. //Assuming here that "size" parameter is a number
  9350. else if (!isNaN(size)) {
  9351. height = size;
  9352. width = size;
  9353. }
  9354. else {
  9355. Tools.Error("Invalid 'size' parameter !");
  9356. return;
  9357. }
  9358. if (!screenshotCanvas) {
  9359. screenshotCanvas = document.createElement('canvas');
  9360. }
  9361. screenshotCanvas.width = width;
  9362. screenshotCanvas.height = height;
  9363. var renderContext = screenshotCanvas.getContext("2d");
  9364. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9365. var newWidth = width;
  9366. var newHeight = newWidth / ratio;
  9367. if (newHeight > height) {
  9368. newHeight = height;
  9369. newWidth = newHeight * ratio;
  9370. }
  9371. var offsetX = Math.max(0, width - newWidth) / 2;
  9372. var offsetY = Math.max(0, height - newHeight) / 2;
  9373. var renderingCanvas = engine.getRenderingCanvas();
  9374. if (renderContext && renderingCanvas) {
  9375. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9376. }
  9377. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9378. };
  9379. /**
  9380. * Generates an image screenshot from the specified camera.
  9381. *
  9382. * @param engine The engine to use for rendering
  9383. * @param camera The camera to use for rendering
  9384. * @param size This parameter can be set to a single number or to an object with the
  9385. * following (optional) properties: precision, width, height. If a single number is passed,
  9386. * it will be used for both width and height. If an object is passed, the screenshot size
  9387. * will be derived from the parameters. The precision property is a multiplier allowing
  9388. * rendering at a higher or lower resolution.
  9389. * @param successCallback The callback receives a single parameter which contains the
  9390. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9391. * src parameter of an <img> to display it.
  9392. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9393. * Check your browser for supported MIME types.
  9394. * @param samples Texture samples (default: 1)
  9395. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9396. * @param fileName A name for for the downloaded file.
  9397. * @constructor
  9398. */
  9399. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9400. if (mimeType === void 0) { mimeType = "image/png"; }
  9401. if (samples === void 0) { samples = 1; }
  9402. if (antialiasing === void 0) { antialiasing = false; }
  9403. var width;
  9404. var height;
  9405. //If a precision value is specified
  9406. if (size.precision) {
  9407. width = Math.round(engine.getRenderWidth() * size.precision);
  9408. height = Math.round(width / engine.getAspectRatio(camera));
  9409. size = { width: width, height: height };
  9410. }
  9411. else if (size.width && size.height) {
  9412. width = size.width;
  9413. height = size.height;
  9414. }
  9415. //If passing only width, computing height to keep display canvas ratio.
  9416. else if (size.width && !size.height) {
  9417. width = size.width;
  9418. height = Math.round(width / engine.getAspectRatio(camera));
  9419. size = { width: width, height: height };
  9420. }
  9421. //If passing only height, computing width to keep display canvas ratio.
  9422. else if (size.height && !size.width) {
  9423. height = size.height;
  9424. width = Math.round(height * engine.getAspectRatio(camera));
  9425. size = { width: width, height: height };
  9426. }
  9427. //Assuming here that "size" parameter is a number
  9428. else if (!isNaN(size)) {
  9429. height = size;
  9430. width = size;
  9431. }
  9432. else {
  9433. Tools.Error("Invalid 'size' parameter !");
  9434. return;
  9435. }
  9436. var scene = camera.getScene();
  9437. var previousCamera = null;
  9438. if (scene.activeCamera !== camera) {
  9439. previousCamera = scene.activeCamera;
  9440. scene.activeCamera = camera;
  9441. }
  9442. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9443. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9444. texture.renderList = null;
  9445. texture.samples = samples;
  9446. if (antialiasing) {
  9447. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9448. }
  9449. texture.onAfterRenderObservable.add(function () {
  9450. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9451. });
  9452. scene.incrementRenderId();
  9453. scene.resetCachedMaterial();
  9454. texture.render(true);
  9455. texture.dispose();
  9456. if (previousCamera) {
  9457. scene.activeCamera = previousCamera;
  9458. }
  9459. camera.getProjectionMatrix(true); // Force cache refresh;
  9460. };
  9461. // XHR response validator for local file scenario
  9462. Tools.ValidateXHRData = function (xhr, dataType) {
  9463. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9464. if (dataType === void 0) { dataType = 7; }
  9465. try {
  9466. if (dataType & 1) {
  9467. if (xhr.responseText && xhr.responseText.length > 0) {
  9468. return true;
  9469. }
  9470. else if (dataType === 1) {
  9471. return false;
  9472. }
  9473. }
  9474. if (dataType & 2) {
  9475. // Check header width and height since there is no "TGA" magic number
  9476. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9477. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9478. return true;
  9479. }
  9480. else if (dataType === 2) {
  9481. return false;
  9482. }
  9483. }
  9484. if (dataType & 4) {
  9485. // Check for the "DDS" magic number
  9486. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9487. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9488. return true;
  9489. }
  9490. else {
  9491. return false;
  9492. }
  9493. }
  9494. }
  9495. catch (e) {
  9496. // Global protection
  9497. }
  9498. return false;
  9499. };
  9500. /**
  9501. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9502. * Be aware Math.random() could cause collisions, but:
  9503. * "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"
  9504. */
  9505. Tools.RandomId = function () {
  9506. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9507. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9508. return v.toString(16);
  9509. });
  9510. };
  9511. /**
  9512. * Test if the given uri is a base64 string.
  9513. * @param uri The uri to test
  9514. * @return True if the uri is a base64 string or false otherwise.
  9515. */
  9516. Tools.IsBase64 = function (uri) {
  9517. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9518. };
  9519. /**
  9520. * Decode the given base64 uri.
  9521. * @param uri The uri to decode
  9522. * @return The decoded base64 data.
  9523. */
  9524. Tools.DecodeBase64 = function (uri) {
  9525. var decodedString = atob(uri.split(",")[1]);
  9526. var bufferLength = decodedString.length;
  9527. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9528. for (var i = 0; i < bufferLength; i++) {
  9529. bufferView[i] = decodedString.charCodeAt(i);
  9530. }
  9531. return bufferView.buffer;
  9532. };
  9533. Object.defineProperty(Tools, "NoneLogLevel", {
  9534. get: function () {
  9535. return Tools._NoneLogLevel;
  9536. },
  9537. enumerable: true,
  9538. configurable: true
  9539. });
  9540. Object.defineProperty(Tools, "MessageLogLevel", {
  9541. get: function () {
  9542. return Tools._MessageLogLevel;
  9543. },
  9544. enumerable: true,
  9545. configurable: true
  9546. });
  9547. Object.defineProperty(Tools, "WarningLogLevel", {
  9548. get: function () {
  9549. return Tools._WarningLogLevel;
  9550. },
  9551. enumerable: true,
  9552. configurable: true
  9553. });
  9554. Object.defineProperty(Tools, "ErrorLogLevel", {
  9555. get: function () {
  9556. return Tools._ErrorLogLevel;
  9557. },
  9558. enumerable: true,
  9559. configurable: true
  9560. });
  9561. Object.defineProperty(Tools, "AllLogLevel", {
  9562. get: function () {
  9563. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Tools._AddLogEntry = function (entry) {
  9569. Tools._LogCache = entry + Tools._LogCache;
  9570. if (Tools.OnNewCacheEntry) {
  9571. Tools.OnNewCacheEntry(entry);
  9572. }
  9573. };
  9574. Tools._FormatMessage = function (message) {
  9575. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9576. var date = new Date();
  9577. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9578. };
  9579. Tools._LogDisabled = function (message) {
  9580. // nothing to do
  9581. };
  9582. Tools._LogEnabled = function (message) {
  9583. var formattedMessage = Tools._FormatMessage(message);
  9584. console.log("BJS - " + formattedMessage);
  9585. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9586. Tools._AddLogEntry(entry);
  9587. };
  9588. Tools._WarnDisabled = function (message) {
  9589. // nothing to do
  9590. };
  9591. Tools._WarnEnabled = function (message) {
  9592. var formattedMessage = Tools._FormatMessage(message);
  9593. console.warn("BJS - " + formattedMessage);
  9594. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9595. Tools._AddLogEntry(entry);
  9596. };
  9597. Tools._ErrorDisabled = function (message) {
  9598. // nothing to do
  9599. };
  9600. Tools._ErrorEnabled = function (message) {
  9601. Tools.errorsCount++;
  9602. var formattedMessage = Tools._FormatMessage(message);
  9603. console.error("BJS - " + formattedMessage);
  9604. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9605. Tools._AddLogEntry(entry);
  9606. };
  9607. Object.defineProperty(Tools, "LogCache", {
  9608. get: function () {
  9609. return Tools._LogCache;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Tools.ClearLogCache = function () {
  9615. Tools._LogCache = "";
  9616. Tools.errorsCount = 0;
  9617. };
  9618. Object.defineProperty(Tools, "LogLevels", {
  9619. set: function (level) {
  9620. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9621. Tools.Log = Tools._LogEnabled;
  9622. }
  9623. else {
  9624. Tools.Log = Tools._LogDisabled;
  9625. }
  9626. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9627. Tools.Warn = Tools._WarnEnabled;
  9628. }
  9629. else {
  9630. Tools.Warn = Tools._WarnDisabled;
  9631. }
  9632. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9633. Tools.Error = Tools._ErrorEnabled;
  9634. }
  9635. else {
  9636. Tools.Error = Tools._ErrorDisabled;
  9637. }
  9638. },
  9639. enumerable: true,
  9640. configurable: true
  9641. });
  9642. Tools.IsWindowObjectExist = function () {
  9643. return (typeof window) !== "undefined";
  9644. };
  9645. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9646. get: function () {
  9647. return Tools._PerformanceNoneLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9653. get: function () {
  9654. return Tools._PerformanceUserMarkLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9660. get: function () {
  9661. return Tools._PerformanceConsoleLogLevel;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9667. set: function (level) {
  9668. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9669. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9670. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9671. return;
  9672. }
  9673. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9674. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9675. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9676. return;
  9677. }
  9678. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9679. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9685. };
  9686. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9687. };
  9688. Tools._StartUserMark = function (counterName, condition) {
  9689. if (condition === void 0) { condition = true; }
  9690. if (!Tools._performance) {
  9691. if (!Tools.IsWindowObjectExist()) {
  9692. return;
  9693. }
  9694. Tools._performance = window.performance;
  9695. }
  9696. if (!condition || !Tools._performance.mark) {
  9697. return;
  9698. }
  9699. Tools._performance.mark(counterName + "-Begin");
  9700. };
  9701. Tools._EndUserMark = function (counterName, condition) {
  9702. if (condition === void 0) { condition = true; }
  9703. if (!condition || !Tools._performance.mark) {
  9704. return;
  9705. }
  9706. Tools._performance.mark(counterName + "-End");
  9707. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9708. };
  9709. Tools._StartPerformanceConsole = function (counterName, condition) {
  9710. if (condition === void 0) { condition = true; }
  9711. if (!condition) {
  9712. return;
  9713. }
  9714. Tools._StartUserMark(counterName, condition);
  9715. if (console.time) {
  9716. console.time(counterName);
  9717. }
  9718. };
  9719. Tools._EndPerformanceConsole = function (counterName, condition) {
  9720. if (condition === void 0) { condition = true; }
  9721. if (!condition) {
  9722. return;
  9723. }
  9724. Tools._EndUserMark(counterName, condition);
  9725. if (console.time) {
  9726. console.timeEnd(counterName);
  9727. }
  9728. };
  9729. Object.defineProperty(Tools, "Now", {
  9730. get: function () {
  9731. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9732. return window.performance.now();
  9733. }
  9734. return Date.now();
  9735. },
  9736. enumerable: true,
  9737. configurable: true
  9738. });
  9739. /**
  9740. * This method will return the name of the class used to create the instance of the given object.
  9741. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9742. * @param object the object to get the class name from
  9743. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9744. */
  9745. Tools.GetClassName = function (object, isType) {
  9746. if (isType === void 0) { isType = false; }
  9747. var name = null;
  9748. if (!isType && object.getClassName) {
  9749. name = object.getClassName();
  9750. }
  9751. else {
  9752. if (object instanceof Object) {
  9753. var classObj = isType ? object : Object.getPrototypeOf(object);
  9754. name = classObj.constructor["__bjsclassName__"];
  9755. }
  9756. if (!name) {
  9757. name = typeof object;
  9758. }
  9759. }
  9760. return name;
  9761. };
  9762. Tools.First = function (array, predicate) {
  9763. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9764. var el = array_1[_i];
  9765. if (predicate(el)) {
  9766. return el;
  9767. }
  9768. }
  9769. return null;
  9770. };
  9771. /**
  9772. * This method will return the name of the full name of the class, including its owning module (if any).
  9773. * 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).
  9774. * @param object the object to get the class name from
  9775. * @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.
  9776. */
  9777. Tools.getFullClassName = function (object, isType) {
  9778. if (isType === void 0) { isType = false; }
  9779. var className = null;
  9780. var moduleName = null;
  9781. if (!isType && object.getClassName) {
  9782. className = object.getClassName();
  9783. }
  9784. else {
  9785. if (object instanceof Object) {
  9786. var classObj = isType ? object : Object.getPrototypeOf(object);
  9787. className = classObj.constructor["__bjsclassName__"];
  9788. moduleName = classObj.constructor["__bjsmoduleName__"];
  9789. }
  9790. if (!className) {
  9791. className = typeof object;
  9792. }
  9793. }
  9794. if (!className) {
  9795. return null;
  9796. }
  9797. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9798. };
  9799. /**
  9800. * 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.
  9801. * @param array
  9802. */
  9803. Tools.arrayOrStringFeeder = function (array) {
  9804. return function (index) {
  9805. if (index >= array.length) {
  9806. return null;
  9807. }
  9808. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9809. if (val && val.getHashCode) {
  9810. val = val.getHashCode();
  9811. }
  9812. if (typeof val === "string") {
  9813. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9814. }
  9815. return val;
  9816. };
  9817. };
  9818. /**
  9819. * Compute the hashCode of a stream of number
  9820. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9821. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9822. * @return the hash code computed
  9823. */
  9824. Tools.hashCodeFromStream = function (feeder) {
  9825. // Based from here: http://stackoverflow.com/a/7616484/802124
  9826. var hash = 0;
  9827. var index = 0;
  9828. var chr = feeder(index++);
  9829. while (chr != null) {
  9830. hash = ((hash << 5) - hash) + chr;
  9831. hash |= 0; // Convert to 32bit integer
  9832. chr = feeder(index++);
  9833. }
  9834. return hash;
  9835. };
  9836. /**
  9837. * Returns a promise that resolves after the given amount of time.
  9838. * @param delay Number of milliseconds to delay
  9839. * @returns Promise that resolves after the given amount of time
  9840. */
  9841. Tools.DelayAsync = function (delay) {
  9842. return new Promise(function (resolve) {
  9843. setTimeout(function () {
  9844. resolve();
  9845. }, delay);
  9846. });
  9847. };
  9848. Tools.BaseUrl = "";
  9849. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9850. /**
  9851. * Default behaviour for cors in the application.
  9852. * It can be a string if the expected behavior is identical in the entire app.
  9853. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9854. */
  9855. Tools.CorsBehavior = "anonymous";
  9856. Tools.UseFallbackTexture = true;
  9857. /**
  9858. * Use this object to register external classes like custom textures or material
  9859. * to allow the laoders to instantiate them
  9860. */
  9861. Tools.RegisteredExternalClasses = {};
  9862. // Used in case of a texture loading problem
  9863. 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";
  9864. Tools._tmpFloatArray = new Float32Array(1);
  9865. Tools.PreprocessUrl = function (url) {
  9866. return url;
  9867. };
  9868. // Logs
  9869. Tools._NoneLogLevel = 0;
  9870. Tools._MessageLogLevel = 1;
  9871. Tools._WarningLogLevel = 2;
  9872. Tools._ErrorLogLevel = 4;
  9873. Tools._LogCache = "";
  9874. Tools.errorsCount = 0;
  9875. Tools.Log = Tools._LogEnabled;
  9876. Tools.Warn = Tools._WarnEnabled;
  9877. Tools.Error = Tools._ErrorEnabled;
  9878. // Performances
  9879. Tools._PerformanceNoneLogLevel = 0;
  9880. Tools._PerformanceUserMarkLogLevel = 1;
  9881. Tools._PerformanceConsoleLogLevel = 2;
  9882. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9883. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9884. return Tools;
  9885. }());
  9886. BABYLON.Tools = Tools;
  9887. /**
  9888. * This class is used to track a performance counter which is number based.
  9889. * The user has access to many properties which give statistics of different nature
  9890. *
  9891. * The implementer can track two kinds of Performance Counter: time and count
  9892. * 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.
  9893. * 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.
  9894. */
  9895. var PerfCounter = /** @class */ (function () {
  9896. function PerfCounter() {
  9897. this._startMonitoringTime = 0;
  9898. this._min = 0;
  9899. this._max = 0;
  9900. this._average = 0;
  9901. this._lastSecAverage = 0;
  9902. this._current = 0;
  9903. this._totalValueCount = 0;
  9904. this._totalAccumulated = 0;
  9905. this._lastSecAccumulated = 0;
  9906. this._lastSecTime = 0;
  9907. this._lastSecValueCount = 0;
  9908. }
  9909. Object.defineProperty(PerfCounter.prototype, "min", {
  9910. /**
  9911. * Returns the smallest value ever
  9912. */
  9913. get: function () {
  9914. return this._min;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(PerfCounter.prototype, "max", {
  9920. /**
  9921. * Returns the biggest value ever
  9922. */
  9923. get: function () {
  9924. return this._max;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(PerfCounter.prototype, "average", {
  9930. /**
  9931. * Returns the average value since the performance counter is running
  9932. */
  9933. get: function () {
  9934. return this._average;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9940. /**
  9941. * Returns the average value of the last second the counter was monitored
  9942. */
  9943. get: function () {
  9944. return this._lastSecAverage;
  9945. },
  9946. enumerable: true,
  9947. configurable: true
  9948. });
  9949. Object.defineProperty(PerfCounter.prototype, "current", {
  9950. /**
  9951. * Returns the current value
  9952. */
  9953. get: function () {
  9954. return this._current;
  9955. },
  9956. enumerable: true,
  9957. configurable: true
  9958. });
  9959. Object.defineProperty(PerfCounter.prototype, "total", {
  9960. get: function () {
  9961. return this._totalAccumulated;
  9962. },
  9963. enumerable: true,
  9964. configurable: true
  9965. });
  9966. Object.defineProperty(PerfCounter.prototype, "count", {
  9967. get: function () {
  9968. return this._totalValueCount;
  9969. },
  9970. enumerable: true,
  9971. configurable: true
  9972. });
  9973. /**
  9974. * Call this method to start monitoring a new frame.
  9975. * 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.
  9976. */
  9977. PerfCounter.prototype.fetchNewFrame = function () {
  9978. this._totalValueCount++;
  9979. this._current = 0;
  9980. this._lastSecValueCount++;
  9981. };
  9982. /**
  9983. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9984. * @param newCount the count value to add to the monitored count
  9985. * @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.
  9986. */
  9987. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9988. if (!PerfCounter.Enabled) {
  9989. return;
  9990. }
  9991. this._current += newCount;
  9992. if (fetchResult) {
  9993. this._fetchResult();
  9994. }
  9995. };
  9996. /**
  9997. * Start monitoring this performance counter
  9998. */
  9999. PerfCounter.prototype.beginMonitoring = function () {
  10000. if (!PerfCounter.Enabled) {
  10001. return;
  10002. }
  10003. this._startMonitoringTime = Tools.Now;
  10004. };
  10005. /**
  10006. * Compute the time lapsed since the previous beginMonitoring() call.
  10007. * @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
  10008. */
  10009. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10010. if (newFrame === void 0) { newFrame = true; }
  10011. if (!PerfCounter.Enabled) {
  10012. return;
  10013. }
  10014. if (newFrame) {
  10015. this.fetchNewFrame();
  10016. }
  10017. var currentTime = Tools.Now;
  10018. this._current = currentTime - this._startMonitoringTime;
  10019. if (newFrame) {
  10020. this._fetchResult();
  10021. }
  10022. };
  10023. PerfCounter.prototype._fetchResult = function () {
  10024. this._totalAccumulated += this._current;
  10025. this._lastSecAccumulated += this._current;
  10026. // Min/Max update
  10027. this._min = Math.min(this._min, this._current);
  10028. this._max = Math.max(this._max, this._current);
  10029. this._average = this._totalAccumulated / this._totalValueCount;
  10030. // Reset last sec?
  10031. var now = Tools.Now;
  10032. if ((now - this._lastSecTime) > 1000) {
  10033. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10034. this._lastSecTime = now;
  10035. this._lastSecAccumulated = 0;
  10036. this._lastSecValueCount = 0;
  10037. }
  10038. };
  10039. PerfCounter.Enabled = true;
  10040. return PerfCounter;
  10041. }());
  10042. BABYLON.PerfCounter = PerfCounter;
  10043. /**
  10044. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10045. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10046. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10047. * @param name The name of the class, case should be preserved
  10048. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10049. */
  10050. function className(name, module) {
  10051. return function (target) {
  10052. target["__bjsclassName__"] = name;
  10053. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10054. };
  10055. }
  10056. BABYLON.className = className;
  10057. /**
  10058. * An implementation of a loop for asynchronous functions.
  10059. */
  10060. var AsyncLoop = /** @class */ (function () {
  10061. /**
  10062. * Constroctor.
  10063. * @param iterations the number of iterations.
  10064. * @param _fn the function to run each iteration
  10065. * @param _successCallback the callback that will be called upon succesful execution
  10066. * @param offset starting offset.
  10067. */
  10068. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10069. if (offset === void 0) { offset = 0; }
  10070. this.iterations = iterations;
  10071. this._fn = _fn;
  10072. this._successCallback = _successCallback;
  10073. this.index = offset - 1;
  10074. this._done = false;
  10075. }
  10076. /**
  10077. * Execute the next iteration. Must be called after the last iteration was finished.
  10078. */
  10079. AsyncLoop.prototype.executeNext = function () {
  10080. if (!this._done) {
  10081. if (this.index + 1 < this.iterations) {
  10082. ++this.index;
  10083. this._fn(this);
  10084. }
  10085. else {
  10086. this.breakLoop();
  10087. }
  10088. }
  10089. };
  10090. /**
  10091. * Break the loop and run the success callback.
  10092. */
  10093. AsyncLoop.prototype.breakLoop = function () {
  10094. this._done = true;
  10095. this._successCallback();
  10096. };
  10097. /**
  10098. * Helper function
  10099. */
  10100. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10101. if (offset === void 0) { offset = 0; }
  10102. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10103. loop.executeNext();
  10104. return loop;
  10105. };
  10106. /**
  10107. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10108. * @param iterations total number of iterations
  10109. * @param syncedIterations number of synchronous iterations in each async iteration.
  10110. * @param fn the function to call each iteration.
  10111. * @param callback a success call back that will be called when iterating stops.
  10112. * @param breakFunction a break condition (optional)
  10113. * @param timeout timeout settings for the setTimeout function. default - 0.
  10114. * @constructor
  10115. */
  10116. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10117. if (timeout === void 0) { timeout = 0; }
  10118. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10119. if (breakFunction && breakFunction())
  10120. loop.breakLoop();
  10121. else {
  10122. setTimeout(function () {
  10123. for (var i = 0; i < syncedIterations; ++i) {
  10124. var iteration = (loop.index * syncedIterations) + i;
  10125. if (iteration >= iterations)
  10126. break;
  10127. fn(iteration);
  10128. if (breakFunction && breakFunction()) {
  10129. loop.breakLoop();
  10130. break;
  10131. }
  10132. }
  10133. loop.executeNext();
  10134. }, timeout);
  10135. }
  10136. }, callback);
  10137. };
  10138. return AsyncLoop;
  10139. }());
  10140. BABYLON.AsyncLoop = AsyncLoop;
  10141. })(BABYLON || (BABYLON = {}));
  10142. //# sourceMappingURL=babylon.tools.js.map
  10143. var BABYLON;
  10144. (function (BABYLON) {
  10145. var PromiseStates;
  10146. (function (PromiseStates) {
  10147. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10148. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10149. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10150. })(PromiseStates || (PromiseStates = {}));
  10151. var FulFillmentAgregator = /** @class */ (function () {
  10152. function FulFillmentAgregator() {
  10153. this.count = 0;
  10154. this.target = 0;
  10155. this.results = [];
  10156. }
  10157. return FulFillmentAgregator;
  10158. }());
  10159. var InternalPromise = /** @class */ (function () {
  10160. function InternalPromise(resolver) {
  10161. var _this = this;
  10162. this._state = PromiseStates.Pending;
  10163. this._children = new Array();
  10164. this._rejectWasConsumed = false;
  10165. if (!resolver) {
  10166. return;
  10167. }
  10168. try {
  10169. resolver(function (value) {
  10170. _this._resolve(value);
  10171. }, function (reason) {
  10172. _this._reject(reason);
  10173. });
  10174. }
  10175. catch (e) {
  10176. this._reject(e);
  10177. }
  10178. }
  10179. Object.defineProperty(InternalPromise.prototype, "_result", {
  10180. get: function () {
  10181. return this._resultValue;
  10182. },
  10183. set: function (value) {
  10184. this._resultValue = value;
  10185. if (this._parent && this._parent._result === undefined) {
  10186. this._parent._result = value;
  10187. }
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. InternalPromise.prototype.catch = function (onRejected) {
  10193. return this.then(undefined, onRejected);
  10194. };
  10195. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10196. var _this = this;
  10197. var newPromise = new InternalPromise();
  10198. newPromise._onFulfilled = onFulfilled;
  10199. newPromise._onRejected = onRejected;
  10200. // Composition
  10201. this._children.push(newPromise);
  10202. newPromise._parent = this;
  10203. if (this._state !== PromiseStates.Pending) {
  10204. BABYLON.Tools.SetImmediate(function () {
  10205. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10206. var returnedValue = newPromise._resolve(_this._result);
  10207. if (returnedValue !== undefined && returnedValue !== null) {
  10208. if (returnedValue._state !== undefined) {
  10209. var returnedPromise = returnedValue;
  10210. newPromise._children.push(returnedPromise);
  10211. returnedPromise._parent = newPromise;
  10212. newPromise = returnedPromise;
  10213. }
  10214. else {
  10215. newPromise._result = returnedValue;
  10216. }
  10217. }
  10218. }
  10219. else {
  10220. newPromise._reject(_this._reason);
  10221. }
  10222. });
  10223. }
  10224. return newPromise;
  10225. };
  10226. InternalPromise.prototype._moveChildren = function (children) {
  10227. var _this = this;
  10228. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10229. this._children.forEach(function (child) {
  10230. child._parent = _this;
  10231. });
  10232. if (this._state === PromiseStates.Fulfilled) {
  10233. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10234. var child = _b[_i];
  10235. child._resolve(this._result);
  10236. }
  10237. }
  10238. else if (this._state === PromiseStates.Rejected) {
  10239. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10240. var child = _d[_c];
  10241. child._reject(this._reason);
  10242. }
  10243. }
  10244. var _a;
  10245. };
  10246. InternalPromise.prototype._resolve = function (value) {
  10247. try {
  10248. this._state = PromiseStates.Fulfilled;
  10249. var returnedValue = null;
  10250. if (this._onFulfilled) {
  10251. returnedValue = this._onFulfilled(value);
  10252. }
  10253. if (returnedValue !== undefined && returnedValue !== null) {
  10254. if (returnedValue._state !== undefined) {
  10255. // Transmit children
  10256. var returnedPromise = returnedValue;
  10257. returnedPromise._parent = this;
  10258. returnedPromise._moveChildren(this._children);
  10259. value = returnedPromise._result;
  10260. }
  10261. else {
  10262. value = returnedValue;
  10263. }
  10264. }
  10265. this._result = value;
  10266. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10267. var child = _a[_i];
  10268. child._resolve(value);
  10269. }
  10270. this._children.length = 0;
  10271. delete this._onFulfilled;
  10272. delete this._onRejected;
  10273. }
  10274. catch (e) {
  10275. this._reject(e, true);
  10276. }
  10277. };
  10278. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10279. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10280. this._state = PromiseStates.Rejected;
  10281. this._reason = reason;
  10282. if (this._onRejected && !onLocalThrow) {
  10283. try {
  10284. this._onRejected(reason);
  10285. this._rejectWasConsumed = true;
  10286. }
  10287. catch (e) {
  10288. reason = e;
  10289. }
  10290. }
  10291. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10292. var child = _a[_i];
  10293. if (this._rejectWasConsumed) {
  10294. child._resolve(null);
  10295. }
  10296. else {
  10297. child._reject(reason);
  10298. }
  10299. }
  10300. this._children.length = 0;
  10301. delete this._onFulfilled;
  10302. delete this._onRejected;
  10303. };
  10304. InternalPromise.resolve = function (value) {
  10305. var newPromise = new InternalPromise();
  10306. newPromise._resolve(value);
  10307. return newPromise;
  10308. };
  10309. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10310. promise.then(function (value) {
  10311. agregator.results[index] = value;
  10312. agregator.count++;
  10313. if (agregator.count === agregator.target) {
  10314. agregator.rootPromise._resolve(agregator.results);
  10315. }
  10316. return null;
  10317. }, function (reason) {
  10318. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10319. agregator.rootPromise._reject(reason);
  10320. }
  10321. });
  10322. };
  10323. InternalPromise.all = function (promises) {
  10324. var newPromise = new InternalPromise();
  10325. var agregator = new FulFillmentAgregator();
  10326. agregator.target = promises.length;
  10327. agregator.rootPromise = newPromise;
  10328. if (promises.length) {
  10329. for (var index = 0; index < promises.length; index++) {
  10330. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10331. }
  10332. }
  10333. else {
  10334. newPromise._resolve([]);
  10335. }
  10336. return newPromise;
  10337. };
  10338. InternalPromise.race = function (promises) {
  10339. var newPromise = new InternalPromise();
  10340. if (promises.length) {
  10341. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10342. var promise = promises_1[_i];
  10343. promise.then(function (value) {
  10344. if (newPromise) {
  10345. newPromise._resolve(value);
  10346. newPromise = null;
  10347. }
  10348. return null;
  10349. }, function (reason) {
  10350. if (newPromise) {
  10351. newPromise._reject(reason);
  10352. newPromise = null;
  10353. }
  10354. });
  10355. }
  10356. }
  10357. return newPromise;
  10358. };
  10359. return InternalPromise;
  10360. }());
  10361. /**
  10362. * Helper class that provides a small promise polyfill
  10363. */
  10364. var PromisePolyfill = /** @class */ (function () {
  10365. function PromisePolyfill() {
  10366. }
  10367. /**
  10368. * Static function used to check if the polyfill is required
  10369. * If this is the case then the function will inject the polyfill to window.Promise
  10370. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10371. */
  10372. PromisePolyfill.Apply = function (force) {
  10373. if (force === void 0) { force = false; }
  10374. if (force || typeof Promise === 'undefined') {
  10375. var root = window;
  10376. root.Promise = InternalPromise;
  10377. }
  10378. };
  10379. return PromisePolyfill;
  10380. }());
  10381. BABYLON.PromisePolyfill = PromisePolyfill;
  10382. })(BABYLON || (BABYLON = {}));
  10383. //# sourceMappingURL=babylon.promise.js.map
  10384. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10385. var BABYLON;
  10386. (function (BABYLON) {
  10387. /**
  10388. * Helper class to push actions to a pool of workers.
  10389. */
  10390. var WorkerPool = /** @class */ (function () {
  10391. /**
  10392. * Constructor
  10393. * @param workers Array of workers to use for actions
  10394. */
  10395. function WorkerPool(workers) {
  10396. this._pendingActions = new Array();
  10397. this._workerInfos = workers.map(function (worker) { return ({
  10398. worker: worker,
  10399. active: false
  10400. }); });
  10401. }
  10402. /**
  10403. * Terminates all workers and clears any pending actions.
  10404. */
  10405. WorkerPool.prototype.dispose = function () {
  10406. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10407. var workerInfo = _a[_i];
  10408. workerInfo.worker.terminate();
  10409. }
  10410. delete this._workerInfos;
  10411. delete this._pendingActions;
  10412. };
  10413. /**
  10414. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10415. * pended until a worker has completed its action.
  10416. * @param action The action to perform. Call onComplete when the action is complete.
  10417. */
  10418. WorkerPool.prototype.push = function (action) {
  10419. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10420. var workerInfo = _a[_i];
  10421. if (!workerInfo.active) {
  10422. this._execute(workerInfo, action);
  10423. return;
  10424. }
  10425. }
  10426. this._pendingActions.push(action);
  10427. };
  10428. WorkerPool.prototype._execute = function (workerInfo, action) {
  10429. var _this = this;
  10430. workerInfo.active = true;
  10431. action(workerInfo.worker, function () {
  10432. workerInfo.active = false;
  10433. var nextAction = _this._pendingActions.shift();
  10434. if (nextAction) {
  10435. _this._execute(workerInfo, nextAction);
  10436. }
  10437. });
  10438. };
  10439. return WorkerPool;
  10440. }());
  10441. BABYLON.WorkerPool = WorkerPool;
  10442. })(BABYLON || (BABYLON = {}));
  10443. //# sourceMappingURL=babylon.workerPool.js.map
  10444. var BABYLON;
  10445. (function (BABYLON) {
  10446. /**
  10447. * @hidden
  10448. **/
  10449. var _AlphaState = /** @class */ (function () {
  10450. /**
  10451. * Initializes the state.
  10452. */
  10453. function _AlphaState() {
  10454. this._isAlphaBlendDirty = false;
  10455. this._isBlendFunctionParametersDirty = false;
  10456. this._isBlendEquationParametersDirty = false;
  10457. this._isBlendConstantsDirty = false;
  10458. this._alphaBlend = false;
  10459. this._blendFunctionParameters = new Array(4);
  10460. this._blendEquationParameters = new Array(2);
  10461. this._blendConstants = new Array(4);
  10462. this.reset();
  10463. }
  10464. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10465. get: function () {
  10466. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10467. },
  10468. enumerable: true,
  10469. configurable: true
  10470. });
  10471. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10472. get: function () {
  10473. return this._alphaBlend;
  10474. },
  10475. set: function (value) {
  10476. if (this._alphaBlend === value) {
  10477. return;
  10478. }
  10479. this._alphaBlend = value;
  10480. this._isAlphaBlendDirty = true;
  10481. },
  10482. enumerable: true,
  10483. configurable: true
  10484. });
  10485. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10486. if (this._blendConstants[0] === r &&
  10487. this._blendConstants[1] === g &&
  10488. this._blendConstants[2] === b &&
  10489. this._blendConstants[3] === a) {
  10490. return;
  10491. }
  10492. this._blendConstants[0] = r;
  10493. this._blendConstants[1] = g;
  10494. this._blendConstants[2] = b;
  10495. this._blendConstants[3] = a;
  10496. this._isBlendConstantsDirty = true;
  10497. };
  10498. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10499. if (this._blendFunctionParameters[0] === value0 &&
  10500. this._blendFunctionParameters[1] === value1 &&
  10501. this._blendFunctionParameters[2] === value2 &&
  10502. this._blendFunctionParameters[3] === value3) {
  10503. return;
  10504. }
  10505. this._blendFunctionParameters[0] = value0;
  10506. this._blendFunctionParameters[1] = value1;
  10507. this._blendFunctionParameters[2] = value2;
  10508. this._blendFunctionParameters[3] = value3;
  10509. this._isBlendFunctionParametersDirty = true;
  10510. };
  10511. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10512. if (this._blendEquationParameters[0] === rgb &&
  10513. this._blendEquationParameters[1] === alpha) {
  10514. return;
  10515. }
  10516. this._blendEquationParameters[0] = rgb;
  10517. this._blendEquationParameters[1] = alpha;
  10518. this._isBlendEquationParametersDirty = true;
  10519. };
  10520. _AlphaState.prototype.reset = function () {
  10521. this._alphaBlend = false;
  10522. this._blendFunctionParameters[0] = null;
  10523. this._blendFunctionParameters[1] = null;
  10524. this._blendFunctionParameters[2] = null;
  10525. this._blendFunctionParameters[3] = null;
  10526. this._blendEquationParameters[0] = null;
  10527. this._blendEquationParameters[1] = null;
  10528. this._blendConstants[0] = null;
  10529. this._blendConstants[1] = null;
  10530. this._blendConstants[2] = null;
  10531. this._blendConstants[3] = null;
  10532. this._isAlphaBlendDirty = true;
  10533. this._isBlendFunctionParametersDirty = false;
  10534. this._isBlendEquationParametersDirty = false;
  10535. this._isBlendConstantsDirty = false;
  10536. };
  10537. _AlphaState.prototype.apply = function (gl) {
  10538. if (!this.isDirty) {
  10539. return;
  10540. }
  10541. // Alpha blend
  10542. if (this._isAlphaBlendDirty) {
  10543. if (this._alphaBlend) {
  10544. gl.enable(gl.BLEND);
  10545. }
  10546. else {
  10547. gl.disable(gl.BLEND);
  10548. }
  10549. this._isAlphaBlendDirty = false;
  10550. }
  10551. // Alpha function
  10552. if (this._isBlendFunctionParametersDirty) {
  10553. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10554. this._isBlendFunctionParametersDirty = false;
  10555. }
  10556. // Alpha equation
  10557. if (this._isBlendEquationParametersDirty) {
  10558. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10559. this._isBlendEquationParametersDirty = false;
  10560. }
  10561. // Constants
  10562. if (this._isBlendConstantsDirty) {
  10563. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10564. this._isBlendConstantsDirty = false;
  10565. }
  10566. };
  10567. return _AlphaState;
  10568. }());
  10569. BABYLON._AlphaState = _AlphaState;
  10570. })(BABYLON || (BABYLON = {}));
  10571. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10572. var BABYLON;
  10573. (function (BABYLON) {
  10574. /**
  10575. * @hidden
  10576. **/
  10577. var _DepthCullingState = /** @class */ (function () {
  10578. /**
  10579. * Initializes the state.
  10580. */
  10581. function _DepthCullingState() {
  10582. this._isDepthTestDirty = false;
  10583. this._isDepthMaskDirty = false;
  10584. this._isDepthFuncDirty = false;
  10585. this._isCullFaceDirty = false;
  10586. this._isCullDirty = false;
  10587. this._isZOffsetDirty = false;
  10588. this._isFrontFaceDirty = false;
  10589. this.reset();
  10590. }
  10591. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10592. get: function () {
  10593. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10594. },
  10595. enumerable: true,
  10596. configurable: true
  10597. });
  10598. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10599. get: function () {
  10600. return this._zOffset;
  10601. },
  10602. set: function (value) {
  10603. if (this._zOffset === value) {
  10604. return;
  10605. }
  10606. this._zOffset = value;
  10607. this._isZOffsetDirty = true;
  10608. },
  10609. enumerable: true,
  10610. configurable: true
  10611. });
  10612. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10613. get: function () {
  10614. return this._cullFace;
  10615. },
  10616. set: function (value) {
  10617. if (this._cullFace === value) {
  10618. return;
  10619. }
  10620. this._cullFace = value;
  10621. this._isCullFaceDirty = true;
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10627. get: function () {
  10628. return this._cull;
  10629. },
  10630. set: function (value) {
  10631. if (this._cull === value) {
  10632. return;
  10633. }
  10634. this._cull = value;
  10635. this._isCullDirty = true;
  10636. },
  10637. enumerable: true,
  10638. configurable: true
  10639. });
  10640. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10641. get: function () {
  10642. return this._depthFunc;
  10643. },
  10644. set: function (value) {
  10645. if (this._depthFunc === value) {
  10646. return;
  10647. }
  10648. this._depthFunc = value;
  10649. this._isDepthFuncDirty = true;
  10650. },
  10651. enumerable: true,
  10652. configurable: true
  10653. });
  10654. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10655. get: function () {
  10656. return this._depthMask;
  10657. },
  10658. set: function (value) {
  10659. if (this._depthMask === value) {
  10660. return;
  10661. }
  10662. this._depthMask = value;
  10663. this._isDepthMaskDirty = true;
  10664. },
  10665. enumerable: true,
  10666. configurable: true
  10667. });
  10668. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10669. get: function () {
  10670. return this._depthTest;
  10671. },
  10672. set: function (value) {
  10673. if (this._depthTest === value) {
  10674. return;
  10675. }
  10676. this._depthTest = value;
  10677. this._isDepthTestDirty = true;
  10678. },
  10679. enumerable: true,
  10680. configurable: true
  10681. });
  10682. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10683. get: function () {
  10684. return this._frontFace;
  10685. },
  10686. set: function (value) {
  10687. if (this._frontFace === value) {
  10688. return;
  10689. }
  10690. this._frontFace = value;
  10691. this._isFrontFaceDirty = true;
  10692. },
  10693. enumerable: true,
  10694. configurable: true
  10695. });
  10696. _DepthCullingState.prototype.reset = function () {
  10697. this._depthMask = true;
  10698. this._depthTest = true;
  10699. this._depthFunc = null;
  10700. this._cullFace = null;
  10701. this._cull = null;
  10702. this._zOffset = 0;
  10703. this._frontFace = null;
  10704. this._isDepthTestDirty = true;
  10705. this._isDepthMaskDirty = true;
  10706. this._isDepthFuncDirty = false;
  10707. this._isCullFaceDirty = false;
  10708. this._isCullDirty = false;
  10709. this._isZOffsetDirty = false;
  10710. this._isFrontFaceDirty = false;
  10711. };
  10712. _DepthCullingState.prototype.apply = function (gl) {
  10713. if (!this.isDirty) {
  10714. return;
  10715. }
  10716. // Cull
  10717. if (this._isCullDirty) {
  10718. if (this.cull) {
  10719. gl.enable(gl.CULL_FACE);
  10720. }
  10721. else {
  10722. gl.disable(gl.CULL_FACE);
  10723. }
  10724. this._isCullDirty = false;
  10725. }
  10726. // Cull face
  10727. if (this._isCullFaceDirty) {
  10728. gl.cullFace(this.cullFace);
  10729. this._isCullFaceDirty = false;
  10730. }
  10731. // Depth mask
  10732. if (this._isDepthMaskDirty) {
  10733. gl.depthMask(this.depthMask);
  10734. this._isDepthMaskDirty = false;
  10735. }
  10736. // Depth test
  10737. if (this._isDepthTestDirty) {
  10738. if (this.depthTest) {
  10739. gl.enable(gl.DEPTH_TEST);
  10740. }
  10741. else {
  10742. gl.disable(gl.DEPTH_TEST);
  10743. }
  10744. this._isDepthTestDirty = false;
  10745. }
  10746. // Depth func
  10747. if (this._isDepthFuncDirty) {
  10748. gl.depthFunc(this.depthFunc);
  10749. this._isDepthFuncDirty = false;
  10750. }
  10751. // zOffset
  10752. if (this._isZOffsetDirty) {
  10753. if (this.zOffset) {
  10754. gl.enable(gl.POLYGON_OFFSET_FILL);
  10755. gl.polygonOffset(this.zOffset, 0);
  10756. }
  10757. else {
  10758. gl.disable(gl.POLYGON_OFFSET_FILL);
  10759. }
  10760. this._isZOffsetDirty = false;
  10761. }
  10762. // Front face
  10763. if (this._isFrontFaceDirty) {
  10764. gl.frontFace(this.frontFace);
  10765. this._isFrontFaceDirty = false;
  10766. }
  10767. };
  10768. return _DepthCullingState;
  10769. }());
  10770. BABYLON._DepthCullingState = _DepthCullingState;
  10771. })(BABYLON || (BABYLON = {}));
  10772. //# sourceMappingURL=babylon.depthCullingState.js.map
  10773. var BABYLON;
  10774. (function (BABYLON) {
  10775. /**
  10776. * @hidden
  10777. **/
  10778. var _StencilState = /** @class */ (function () {
  10779. function _StencilState() {
  10780. this._isStencilTestDirty = false;
  10781. this._isStencilMaskDirty = false;
  10782. this._isStencilFuncDirty = false;
  10783. this._isStencilOpDirty = false;
  10784. this.reset();
  10785. }
  10786. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10787. get: function () {
  10788. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10789. },
  10790. enumerable: true,
  10791. configurable: true
  10792. });
  10793. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10794. get: function () {
  10795. return this._stencilFunc;
  10796. },
  10797. set: function (value) {
  10798. if (this._stencilFunc === value) {
  10799. return;
  10800. }
  10801. this._stencilFunc = value;
  10802. this._isStencilFuncDirty = true;
  10803. },
  10804. enumerable: true,
  10805. configurable: true
  10806. });
  10807. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10808. get: function () {
  10809. return this._stencilFuncRef;
  10810. },
  10811. set: function (value) {
  10812. if (this._stencilFuncRef === value) {
  10813. return;
  10814. }
  10815. this._stencilFuncRef = value;
  10816. this._isStencilFuncDirty = true;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10822. get: function () {
  10823. return this._stencilFuncMask;
  10824. },
  10825. set: function (value) {
  10826. if (this._stencilFuncMask === value) {
  10827. return;
  10828. }
  10829. this._stencilFuncMask = value;
  10830. this._isStencilFuncDirty = true;
  10831. },
  10832. enumerable: true,
  10833. configurable: true
  10834. });
  10835. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10836. get: function () {
  10837. return this._stencilOpStencilFail;
  10838. },
  10839. set: function (value) {
  10840. if (this._stencilOpStencilFail === value) {
  10841. return;
  10842. }
  10843. this._stencilOpStencilFail = value;
  10844. this._isStencilOpDirty = true;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10850. get: function () {
  10851. return this._stencilOpDepthFail;
  10852. },
  10853. set: function (value) {
  10854. if (this._stencilOpDepthFail === value) {
  10855. return;
  10856. }
  10857. this._stencilOpDepthFail = value;
  10858. this._isStencilOpDirty = true;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10864. get: function () {
  10865. return this._stencilOpStencilDepthPass;
  10866. },
  10867. set: function (value) {
  10868. if (this._stencilOpStencilDepthPass === value) {
  10869. return;
  10870. }
  10871. this._stencilOpStencilDepthPass = value;
  10872. this._isStencilOpDirty = true;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10878. get: function () {
  10879. return this._stencilMask;
  10880. },
  10881. set: function (value) {
  10882. if (this._stencilMask === value) {
  10883. return;
  10884. }
  10885. this._stencilMask = value;
  10886. this._isStencilMaskDirty = true;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10892. get: function () {
  10893. return this._stencilTest;
  10894. },
  10895. set: function (value) {
  10896. if (this._stencilTest === value) {
  10897. return;
  10898. }
  10899. this._stencilTest = value;
  10900. this._isStencilTestDirty = true;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. _StencilState.prototype.reset = function () {
  10906. this._stencilTest = false;
  10907. this._stencilMask = 0xFF;
  10908. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10909. this._stencilFuncRef = 1;
  10910. this._stencilFuncMask = 0xFF;
  10911. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10912. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10913. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10914. this._isStencilTestDirty = true;
  10915. this._isStencilMaskDirty = true;
  10916. this._isStencilFuncDirty = true;
  10917. this._isStencilOpDirty = true;
  10918. };
  10919. _StencilState.prototype.apply = function (gl) {
  10920. if (!this.isDirty) {
  10921. return;
  10922. }
  10923. // Stencil test
  10924. if (this._isStencilTestDirty) {
  10925. if (this.stencilTest) {
  10926. gl.enable(gl.STENCIL_TEST);
  10927. }
  10928. else {
  10929. gl.disable(gl.STENCIL_TEST);
  10930. }
  10931. this._isStencilTestDirty = false;
  10932. }
  10933. // Stencil mask
  10934. if (this._isStencilMaskDirty) {
  10935. gl.stencilMask(this.stencilMask);
  10936. this._isStencilMaskDirty = false;
  10937. }
  10938. // Stencil func
  10939. if (this._isStencilFuncDirty) {
  10940. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10941. this._isStencilFuncDirty = false;
  10942. }
  10943. // Stencil op
  10944. if (this._isStencilOpDirty) {
  10945. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10946. this._isStencilOpDirty = false;
  10947. }
  10948. };
  10949. return _StencilState;
  10950. }());
  10951. BABYLON._StencilState = _StencilState;
  10952. })(BABYLON || (BABYLON = {}));
  10953. //# sourceMappingURL=babylon.stencilState.js.map
  10954. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10955. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10956. s = arguments[i];
  10957. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10958. t[p] = s[p];
  10959. }
  10960. return t;
  10961. };
  10962. var BABYLON;
  10963. (function (BABYLON) {
  10964. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10965. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10966. };
  10967. var compileRawShader = function (gl, source, type) {
  10968. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10969. gl.shaderSource(shader, source);
  10970. gl.compileShader(shader);
  10971. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10972. var log = gl.getShaderInfoLog(shader);
  10973. if (log) {
  10974. throw new Error(log);
  10975. }
  10976. }
  10977. if (!shader) {
  10978. throw new Error("Something went wrong while compile the shader.");
  10979. }
  10980. return shader;
  10981. };
  10982. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10983. var magFilter = gl.NEAREST;
  10984. var minFilter = gl.NEAREST;
  10985. switch (samplingMode) {
  10986. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10987. magFilter = gl.LINEAR;
  10988. if (generateMipMaps) {
  10989. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10990. }
  10991. else {
  10992. minFilter = gl.LINEAR;
  10993. }
  10994. break;
  10995. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10996. magFilter = gl.LINEAR;
  10997. if (generateMipMaps) {
  10998. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10999. }
  11000. else {
  11001. minFilter = gl.LINEAR;
  11002. }
  11003. break;
  11004. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11005. magFilter = gl.NEAREST;
  11006. if (generateMipMaps) {
  11007. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11008. }
  11009. else {
  11010. minFilter = gl.NEAREST;
  11011. }
  11012. break;
  11013. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11014. magFilter = gl.NEAREST;
  11015. if (generateMipMaps) {
  11016. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11017. }
  11018. else {
  11019. minFilter = gl.NEAREST;
  11020. }
  11021. break;
  11022. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11023. magFilter = gl.NEAREST;
  11024. if (generateMipMaps) {
  11025. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11026. }
  11027. else {
  11028. minFilter = gl.LINEAR;
  11029. }
  11030. break;
  11031. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11032. magFilter = gl.NEAREST;
  11033. if (generateMipMaps) {
  11034. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11035. }
  11036. else {
  11037. minFilter = gl.LINEAR;
  11038. }
  11039. break;
  11040. case BABYLON.Texture.NEAREST_LINEAR:
  11041. magFilter = gl.NEAREST;
  11042. minFilter = gl.LINEAR;
  11043. break;
  11044. case BABYLON.Texture.NEAREST_NEAREST:
  11045. magFilter = gl.NEAREST;
  11046. minFilter = gl.NEAREST;
  11047. break;
  11048. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11049. magFilter = gl.LINEAR;
  11050. if (generateMipMaps) {
  11051. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11052. }
  11053. else {
  11054. minFilter = gl.NEAREST;
  11055. }
  11056. break;
  11057. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11058. magFilter = gl.LINEAR;
  11059. if (generateMipMaps) {
  11060. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11061. }
  11062. else {
  11063. minFilter = gl.NEAREST;
  11064. }
  11065. break;
  11066. case BABYLON.Texture.LINEAR_LINEAR:
  11067. magFilter = gl.LINEAR;
  11068. minFilter = gl.LINEAR;
  11069. break;
  11070. case BABYLON.Texture.LINEAR_NEAREST:
  11071. magFilter = gl.LINEAR;
  11072. minFilter = gl.NEAREST;
  11073. break;
  11074. }
  11075. return {
  11076. min: minFilter,
  11077. mag: magFilter
  11078. };
  11079. };
  11080. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11081. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11082. var img;
  11083. var onload = function () {
  11084. loadedImages[index] = img;
  11085. loadedImages._internalCount++;
  11086. if (scene) {
  11087. scene._removePendingData(img);
  11088. }
  11089. if (loadedImages._internalCount === 6) {
  11090. onfinish(loadedImages);
  11091. }
  11092. };
  11093. var onerror = function (message, exception) {
  11094. if (scene) {
  11095. scene._removePendingData(img);
  11096. }
  11097. if (onErrorCallBack) {
  11098. onErrorCallBack(message, exception);
  11099. }
  11100. };
  11101. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11102. if (scene) {
  11103. scene._addPendingData(img);
  11104. }
  11105. };
  11106. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11107. if (onError === void 0) { onError = null; }
  11108. var loadedImages = [];
  11109. loadedImages._internalCount = 0;
  11110. for (var index = 0; index < 6; index++) {
  11111. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11112. }
  11113. };
  11114. var BufferPointer = /** @class */ (function () {
  11115. function BufferPointer() {
  11116. }
  11117. return BufferPointer;
  11118. }());
  11119. /**
  11120. * Interface for attribute information associated with buffer instanciation
  11121. */
  11122. var InstancingAttributeInfo = /** @class */ (function () {
  11123. function InstancingAttributeInfo() {
  11124. }
  11125. return InstancingAttributeInfo;
  11126. }());
  11127. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11128. /**
  11129. * Define options used to create a render target texture
  11130. */
  11131. var RenderTargetCreationOptions = /** @class */ (function () {
  11132. function RenderTargetCreationOptions() {
  11133. }
  11134. return RenderTargetCreationOptions;
  11135. }());
  11136. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11137. /**
  11138. * Define options used to create a depth texture
  11139. */
  11140. var DepthTextureCreationOptions = /** @class */ (function () {
  11141. function DepthTextureCreationOptions() {
  11142. }
  11143. return DepthTextureCreationOptions;
  11144. }());
  11145. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11146. /**
  11147. * Class used to describe the capabilities of the engine relatively to the current browser
  11148. */
  11149. var EngineCapabilities = /** @class */ (function () {
  11150. function EngineCapabilities() {
  11151. }
  11152. return EngineCapabilities;
  11153. }());
  11154. BABYLON.EngineCapabilities = EngineCapabilities;
  11155. /**
  11156. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11157. */
  11158. var Engine = /** @class */ (function () {
  11159. /**
  11160. * Creates a new engine
  11161. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11162. * @param antialias defines enable antialiasing (default: false)
  11163. * @param options defines further options to be sent to the getContext() function
  11164. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11165. */
  11166. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11167. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11168. var _this = this;
  11169. // Public members
  11170. /**
  11171. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11172. */
  11173. this.forcePOTTextures = false;
  11174. /**
  11175. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11176. */
  11177. this.isFullscreen = false;
  11178. /**
  11179. * Gets a boolean indicating if the pointer is currently locked
  11180. */
  11181. this.isPointerLock = false;
  11182. /**
  11183. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11184. */
  11185. this.cullBackFaces = true;
  11186. /**
  11187. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11188. */
  11189. this.renderEvenInBackground = true;
  11190. /**
  11191. * Gets or sets a boolean indicating that cache can be kept between frames
  11192. */
  11193. this.preventCacheWipeBetweenFrames = false;
  11194. /**
  11195. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11196. **/
  11197. this.enableOfflineSupport = false;
  11198. /**
  11199. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11200. **/
  11201. this.disableManifestCheck = false;
  11202. /**
  11203. * Gets the list of created scenes
  11204. */
  11205. this.scenes = new Array();
  11206. /**
  11207. * Gets the list of created postprocesses
  11208. */
  11209. this.postProcesses = new Array();
  11210. // Observables
  11211. /**
  11212. * Observable event triggered each time the rendering canvas is resized
  11213. */
  11214. this.onResizeObservable = new BABYLON.Observable();
  11215. /**
  11216. * Observable event triggered each time the canvas loses focus
  11217. */
  11218. this.onCanvasBlurObservable = new BABYLON.Observable();
  11219. /**
  11220. * Observable event triggered each time the canvas gains focus
  11221. */
  11222. this.onCanvasFocusObservable = new BABYLON.Observable();
  11223. /**
  11224. * Observable event triggered each time the canvas receives pointerout event
  11225. */
  11226. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11227. /**
  11228. * Observable event triggered before each texture is initialized
  11229. */
  11230. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11231. //WebVR
  11232. this._vrDisplay = undefined;
  11233. this._vrSupported = false;
  11234. this._vrExclusivePointerMode = false;
  11235. // Uniform buffers list
  11236. /**
  11237. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11238. */
  11239. this.disableUniformBuffers = false;
  11240. /** @hidden */
  11241. this._uniformBuffers = new Array();
  11242. // Observables
  11243. /**
  11244. * Observable raised when the engine begins a new frame
  11245. */
  11246. this.onBeginFrameObservable = new BABYLON.Observable();
  11247. /**
  11248. * Observable raised when the engine ends the current frame
  11249. */
  11250. this.onEndFrameObservable = new BABYLON.Observable();
  11251. /**
  11252. * Observable raised when the engine is about to compile a shader
  11253. */
  11254. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11255. /**
  11256. * Observable raised when the engine has jsut compiled a shader
  11257. */
  11258. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11259. this._windowIsBackground = false;
  11260. this._webGLVersion = 1.0;
  11261. /** @hidden */
  11262. this._badOS = false;
  11263. /** @hidden */
  11264. this._badDesktopOS = false;
  11265. /**
  11266. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11267. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11268. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11269. */
  11270. this.disableTextureBindingOptimization = false;
  11271. /**
  11272. * Observable signaled when VR display mode changes
  11273. */
  11274. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11275. /**
  11276. * Observable signaled when VR request present is complete
  11277. */
  11278. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11279. /**
  11280. * Observable signaled when VR request present starts
  11281. */
  11282. this.onVRRequestPresentStart = new BABYLON.Observable();
  11283. this._colorWrite = true;
  11284. /** @hidden */
  11285. this._drawCalls = new BABYLON.PerfCounter();
  11286. /** @hidden */
  11287. this._textureCollisions = new BABYLON.PerfCounter();
  11288. this._renderingQueueLaunched = false;
  11289. this._activeRenderLoops = new Array();
  11290. // Deterministic lockstepMaxSteps
  11291. this._deterministicLockstep = false;
  11292. this._lockstepMaxSteps = 4;
  11293. // Lost context
  11294. /**
  11295. * Observable signaled when a context lost event is raised
  11296. */
  11297. this.onContextLostObservable = new BABYLON.Observable();
  11298. /**
  11299. * Observable signaled when a context restored event is raised
  11300. */
  11301. this.onContextRestoredObservable = new BABYLON.Observable();
  11302. this._contextWasLost = false;
  11303. this._doNotHandleContextLost = false;
  11304. // FPS
  11305. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11306. this._fps = 60;
  11307. this._deltaTime = 0;
  11308. /**
  11309. * Turn this value on if you want to pause FPS computation when in background
  11310. */
  11311. this.disablePerformanceMonitorInBackground = false;
  11312. // States
  11313. /** @hidden */
  11314. this._depthCullingState = new BABYLON._DepthCullingState();
  11315. /** @hidden */
  11316. this._stencilState = new BABYLON._StencilState();
  11317. /** @hidden */
  11318. this._alphaState = new BABYLON._AlphaState();
  11319. /** @hidden */
  11320. this._alphaMode = Engine.ALPHA_DISABLE;
  11321. // Cache
  11322. this._internalTexturesCache = new Array();
  11323. /** @hidden */
  11324. this._activeChannel = 0;
  11325. this._currentTextureChannel = -1;
  11326. /** @hidden */
  11327. this._boundTexturesCache = {};
  11328. this._compiledEffects = {};
  11329. this._vertexAttribArraysEnabled = [];
  11330. this._uintIndicesCurrentlySet = false;
  11331. this._currentBoundBuffer = new Array();
  11332. this._currentBufferPointers = new Array();
  11333. this._currentInstanceLocations = new Array();
  11334. this._currentInstanceBuffers = new Array();
  11335. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11336. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11337. this._vaoRecordInProgress = false;
  11338. this._mustWipeVertexAttributes = false;
  11339. this._nextFreeTextureSlots = new Array();
  11340. this._maxSimultaneousTextures = 0;
  11341. this._activeRequests = new Array();
  11342. // Hardware supported Compressed Textures
  11343. this._texturesSupported = new Array();
  11344. this._onVRFullScreenTriggered = function () {
  11345. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11346. //get the old size before we change
  11347. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11348. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11349. //get the width and height, change the render size
  11350. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11351. _this.setHardwareScalingLevel(1);
  11352. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11353. }
  11354. else {
  11355. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11356. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11357. }
  11358. };
  11359. this._boundUniforms = {};
  11360. // Register promises
  11361. BABYLON.PromisePolyfill.Apply();
  11362. var canvas = null;
  11363. Engine.Instances.push(this);
  11364. if (!canvasOrContext) {
  11365. return;
  11366. }
  11367. options = options || {};
  11368. if (canvasOrContext.getContext) {
  11369. canvas = canvasOrContext;
  11370. this._renderingCanvas = canvas;
  11371. if (antialias != null) {
  11372. options.antialias = antialias;
  11373. }
  11374. if (options.deterministicLockstep === undefined) {
  11375. options.deterministicLockstep = false;
  11376. }
  11377. if (options.lockstepMaxSteps === undefined) {
  11378. options.lockstepMaxSteps = 4;
  11379. }
  11380. if (options.preserveDrawingBuffer === undefined) {
  11381. options.preserveDrawingBuffer = false;
  11382. }
  11383. if (options.audioEngine === undefined) {
  11384. options.audioEngine = true;
  11385. }
  11386. if (options.stencil === undefined) {
  11387. options.stencil = true;
  11388. }
  11389. this._deterministicLockstep = options.deterministicLockstep;
  11390. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11391. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11392. // Exceptions
  11393. if (navigator && navigator.userAgent) {
  11394. var ua = navigator.userAgent;
  11395. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11396. var exception = _a[_i];
  11397. var key = exception.key;
  11398. var targets = exception.targets;
  11399. if (ua.indexOf(key) > -1) {
  11400. if (exception.capture && exception.captureConstraint) {
  11401. var capture = exception.capture;
  11402. var constraint = exception.captureConstraint;
  11403. var regex = new RegExp(capture);
  11404. var matches = regex.exec(ua);
  11405. if (matches && matches.length > 0) {
  11406. var capturedValue = parseInt(matches[matches.length - 1]);
  11407. if (capturedValue >= constraint) {
  11408. continue;
  11409. }
  11410. }
  11411. }
  11412. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11413. var target = targets_1[_b];
  11414. switch (target) {
  11415. case "uniformBuffer":
  11416. this.disableUniformBuffers = true;
  11417. break;
  11418. case "textureBindingOptimization":
  11419. this.disableTextureBindingOptimization = true;
  11420. break;
  11421. }
  11422. }
  11423. }
  11424. }
  11425. }
  11426. // GL
  11427. if (!options.disableWebGL2Support) {
  11428. try {
  11429. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11430. if (this._gl) {
  11431. this._webGLVersion = 2.0;
  11432. }
  11433. }
  11434. catch (e) {
  11435. // Do nothing
  11436. }
  11437. }
  11438. if (!this._gl) {
  11439. if (!canvas) {
  11440. throw new Error("The provided canvas is null or undefined.");
  11441. }
  11442. try {
  11443. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11444. }
  11445. catch (e) {
  11446. throw new Error("WebGL not supported");
  11447. }
  11448. }
  11449. if (!this._gl) {
  11450. throw new Error("WebGL not supported");
  11451. }
  11452. this._onCanvasFocus = function () {
  11453. _this.onCanvasFocusObservable.notifyObservers(_this);
  11454. };
  11455. this._onCanvasBlur = function () {
  11456. _this.onCanvasBlurObservable.notifyObservers(_this);
  11457. };
  11458. canvas.addEventListener("focus", this._onCanvasFocus);
  11459. canvas.addEventListener("blur", this._onCanvasBlur);
  11460. this._onBlur = function () {
  11461. if (_this.disablePerformanceMonitorInBackground) {
  11462. _this._performanceMonitor.disable();
  11463. }
  11464. _this._windowIsBackground = true;
  11465. };
  11466. this._onFocus = function () {
  11467. if (_this.disablePerformanceMonitorInBackground) {
  11468. _this._performanceMonitor.enable();
  11469. }
  11470. _this._windowIsBackground = false;
  11471. };
  11472. this._onCanvasPointerOut = function (ev) {
  11473. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11474. };
  11475. window.addEventListener("blur", this._onBlur);
  11476. window.addEventListener("focus", this._onFocus);
  11477. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11478. // Context lost
  11479. if (!this._doNotHandleContextLost) {
  11480. this._onContextLost = function (evt) {
  11481. evt.preventDefault();
  11482. _this._contextWasLost = true;
  11483. BABYLON.Tools.Warn("WebGL context lost.");
  11484. _this.onContextLostObservable.notifyObservers(_this);
  11485. };
  11486. this._onContextRestored = function (evt) {
  11487. // Adding a timeout to avoid race condition at browser level
  11488. setTimeout(function () {
  11489. // Rebuild gl context
  11490. _this._initGLContext();
  11491. // Rebuild effects
  11492. _this._rebuildEffects();
  11493. // Rebuild textures
  11494. _this._rebuildInternalTextures();
  11495. // Rebuild buffers
  11496. _this._rebuildBuffers();
  11497. // Cache
  11498. _this.wipeCaches(true);
  11499. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11500. _this.onContextRestoredObservable.notifyObservers(_this);
  11501. _this._contextWasLost = false;
  11502. }, 0);
  11503. };
  11504. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11505. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11506. }
  11507. }
  11508. else {
  11509. this._gl = canvasOrContext;
  11510. this._renderingCanvas = this._gl.canvas;
  11511. if (this._gl.renderbufferStorageMultisample) {
  11512. this._webGLVersion = 2.0;
  11513. }
  11514. options.stencil = this._gl.getContextAttributes().stencil;
  11515. }
  11516. // Viewport
  11517. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11518. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11519. this.resize();
  11520. this._isStencilEnable = options.stencil ? true : false;
  11521. this._initGLContext();
  11522. if (canvas) {
  11523. // Fullscreen
  11524. this._onFullscreenChange = function () {
  11525. if (document.fullscreen !== undefined) {
  11526. _this.isFullscreen = document.fullscreen;
  11527. }
  11528. else if (document.mozFullScreen !== undefined) {
  11529. _this.isFullscreen = document.mozFullScreen;
  11530. }
  11531. else if (document.webkitIsFullScreen !== undefined) {
  11532. _this.isFullscreen = document.webkitIsFullScreen;
  11533. }
  11534. else if (document.msIsFullScreen !== undefined) {
  11535. _this.isFullscreen = document.msIsFullScreen;
  11536. }
  11537. // Pointer lock
  11538. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11539. canvas.requestPointerLock = canvas.requestPointerLock ||
  11540. canvas.msRequestPointerLock ||
  11541. canvas.mozRequestPointerLock ||
  11542. canvas.webkitRequestPointerLock;
  11543. if (canvas.requestPointerLock) {
  11544. canvas.requestPointerLock();
  11545. }
  11546. }
  11547. };
  11548. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11549. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11550. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11551. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11552. // Pointer lock
  11553. this._onPointerLockChange = function () {
  11554. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11555. document.webkitPointerLockElement === canvas ||
  11556. document.msPointerLockElement === canvas ||
  11557. document.pointerLockElement === canvas);
  11558. };
  11559. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11560. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11561. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11562. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11563. this._onVRDisplayPointerRestricted = function () {
  11564. if (canvas) {
  11565. canvas.requestPointerLock();
  11566. }
  11567. };
  11568. this._onVRDisplayPointerUnrestricted = function () {
  11569. document.exitPointerLock();
  11570. };
  11571. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11572. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11573. }
  11574. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11575. Engine.audioEngine = new BABYLON.AudioEngine();
  11576. }
  11577. // Prepare buffer pointers
  11578. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11579. this._currentBufferPointers[i] = new BufferPointer();
  11580. }
  11581. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11582. // Load WebVR Devices
  11583. if (options.autoEnableWebVR) {
  11584. this.initWebVR();
  11585. }
  11586. // Detect if we are running on a faulty buggy OS.
  11587. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11588. // Detect if we are running on a faulty buggy desktop OS.
  11589. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11590. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11591. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11592. }
  11593. Object.defineProperty(Engine, "LastCreatedEngine", {
  11594. /**
  11595. * Gets the latest created engine
  11596. */
  11597. get: function () {
  11598. if (Engine.Instances.length === 0) {
  11599. return null;
  11600. }
  11601. return Engine.Instances[Engine.Instances.length - 1];
  11602. },
  11603. enumerable: true,
  11604. configurable: true
  11605. });
  11606. Object.defineProperty(Engine, "LastCreatedScene", {
  11607. /**
  11608. * Gets the latest created scene
  11609. */
  11610. get: function () {
  11611. var lastCreatedEngine = Engine.LastCreatedEngine;
  11612. if (!lastCreatedEngine) {
  11613. return null;
  11614. }
  11615. if (lastCreatedEngine.scenes.length === 0) {
  11616. return null;
  11617. }
  11618. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11619. },
  11620. enumerable: true,
  11621. configurable: true
  11622. });
  11623. /**
  11624. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11625. * @param flag defines which part of the materials must be marked as dirty
  11626. * @param predicate defines a predicate used to filter which materials should be affected
  11627. */
  11628. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11629. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11630. var engine = Engine.Instances[engineIndex];
  11631. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11632. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11633. }
  11634. }
  11635. };
  11636. Object.defineProperty(Engine, "NEVER", {
  11637. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11638. get: function () {
  11639. return Engine._NEVER;
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. Object.defineProperty(Engine, "ALWAYS", {
  11645. /** 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 */
  11646. get: function () {
  11647. return Engine._ALWAYS;
  11648. },
  11649. enumerable: true,
  11650. configurable: true
  11651. });
  11652. Object.defineProperty(Engine, "LESS", {
  11653. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11654. get: function () {
  11655. return Engine._LESS;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Engine, "EQUAL", {
  11661. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11662. get: function () {
  11663. return Engine._EQUAL;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "LEQUAL", {
  11669. /** 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 */
  11670. get: function () {
  11671. return Engine._LEQUAL;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Engine, "GREATER", {
  11677. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11678. get: function () {
  11679. return Engine._GREATER;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine, "GEQUAL", {
  11685. /** 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 */
  11686. get: function () {
  11687. return Engine._GEQUAL;
  11688. },
  11689. enumerable: true,
  11690. configurable: true
  11691. });
  11692. Object.defineProperty(Engine, "NOTEQUAL", {
  11693. /** 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 */
  11694. get: function () {
  11695. return Engine._NOTEQUAL;
  11696. },
  11697. enumerable: true,
  11698. configurable: true
  11699. });
  11700. Object.defineProperty(Engine, "KEEP", {
  11701. /** Passed to stencilOperation to specify that stencil value must be kept */
  11702. get: function () {
  11703. return Engine._KEEP;
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Engine, "REPLACE", {
  11709. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11710. get: function () {
  11711. return Engine._REPLACE;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Engine, "INCR", {
  11717. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11718. get: function () {
  11719. return Engine._INCR;
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(Engine, "DECR", {
  11725. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11726. get: function () {
  11727. return Engine._DECR;
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. Object.defineProperty(Engine, "INVERT", {
  11733. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11734. get: function () {
  11735. return Engine._INVERT;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine, "INCR_WRAP", {
  11741. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11742. get: function () {
  11743. return Engine._INCR_WRAP;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Engine, "DECR_WRAP", {
  11749. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11750. get: function () {
  11751. return Engine._DECR_WRAP;
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11757. // Alpha
  11758. /** Defines that alpha blending is disabled */
  11759. get: function () {
  11760. return Engine._ALPHA_DISABLE;
  11761. },
  11762. enumerable: true,
  11763. configurable: true
  11764. });
  11765. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11766. /** Defines that alpha blending to SRC + DEST */
  11767. get: function () {
  11768. return Engine._ALPHA_ONEONE;
  11769. },
  11770. enumerable: true,
  11771. configurable: true
  11772. });
  11773. Object.defineProperty(Engine, "ALPHA_ADD", {
  11774. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11775. get: function () {
  11776. return Engine._ALPHA_ADD;
  11777. },
  11778. enumerable: true,
  11779. configurable: true
  11780. });
  11781. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11782. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11783. get: function () {
  11784. return Engine._ALPHA_COMBINE;
  11785. },
  11786. enumerable: true,
  11787. configurable: true
  11788. });
  11789. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11790. /** Defines that alpha blending to DEST - SRC * DEST */
  11791. get: function () {
  11792. return Engine._ALPHA_SUBTRACT;
  11793. },
  11794. enumerable: true,
  11795. configurable: true
  11796. });
  11797. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11798. /** Defines that alpha blending to SRC * DEST */
  11799. get: function () {
  11800. return Engine._ALPHA_MULTIPLY;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11806. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11807. get: function () {
  11808. return Engine._ALPHA_MAXIMIZED;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11814. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11815. get: function () {
  11816. return Engine._ALPHA_PREMULTIPLIED;
  11817. },
  11818. enumerable: true,
  11819. configurable: true
  11820. });
  11821. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11822. /**
  11823. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11824. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11825. */
  11826. get: function () {
  11827. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11833. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11834. get: function () {
  11835. return Engine._ALPHA_INTERPOLATE;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11841. /**
  11842. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11843. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11844. */
  11845. get: function () {
  11846. return Engine._ALPHA_SCREENMODE;
  11847. },
  11848. enumerable: true,
  11849. configurable: true
  11850. });
  11851. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11852. // Delays
  11853. /** Defines that the ressource is not delayed*/
  11854. get: function () {
  11855. return Engine._DELAYLOADSTATE_NONE;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11861. /** Defines that the ressource was successfully delay loaded */
  11862. get: function () {
  11863. return Engine._DELAYLOADSTATE_LOADED;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11869. /** Defines that the ressource is currently delay loading */
  11870. get: function () {
  11871. return Engine._DELAYLOADSTATE_LOADING;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11877. /** Defines that the ressource is delayed and has not started loading */
  11878. get: function () {
  11879. return Engine._DELAYLOADSTATE_NOTLOADED;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11885. /** ALPHA */
  11886. get: function () {
  11887. return Engine._TEXTUREFORMAT_ALPHA;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11893. /** LUMINANCE */
  11894. get: function () {
  11895. return Engine._TEXTUREFORMAT_LUMINANCE;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11901. /**
  11902. * R32F
  11903. */
  11904. get: function () {
  11905. return Engine._TEXTUREFORMAT_R32F;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11911. /**
  11912. * RG32F
  11913. */
  11914. get: function () {
  11915. return Engine._TEXTUREFORMAT_RG32F;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11921. /**
  11922. * RGB32F
  11923. */
  11924. get: function () {
  11925. return Engine._TEXTUREFORMAT_RGB32F;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11931. /**
  11932. * RGBA32F
  11933. */
  11934. get: function () {
  11935. return Engine._TEXTUREFORMAT_RGBA32F;
  11936. },
  11937. enumerable: true,
  11938. configurable: true
  11939. });
  11940. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11941. /** LUMINANCE_ALPHA */
  11942. get: function () {
  11943. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11944. },
  11945. enumerable: true,
  11946. configurable: true
  11947. });
  11948. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11949. /** RGB */
  11950. get: function () {
  11951. return Engine._TEXTUREFORMAT_RGB;
  11952. },
  11953. enumerable: true,
  11954. configurable: true
  11955. });
  11956. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11957. /** RGBA */
  11958. get: function () {
  11959. return Engine._TEXTUREFORMAT_RGBA;
  11960. },
  11961. enumerable: true,
  11962. configurable: true
  11963. });
  11964. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11965. /** UNSIGNED_INT */
  11966. get: function () {
  11967. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11973. /** FLOAT */
  11974. get: function () {
  11975. return Engine._TEXTURETYPE_FLOAT;
  11976. },
  11977. enumerable: true,
  11978. configurable: true
  11979. });
  11980. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11981. /** HALF_FLOAT */
  11982. get: function () {
  11983. return Engine._TEXTURETYPE_HALF_FLOAT;
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11989. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11990. get: function () {
  11991. return Engine._SCALEMODE_FLOOR;
  11992. },
  11993. enumerable: true,
  11994. configurable: true
  11995. });
  11996. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11997. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11998. get: function () {
  11999. return Engine._SCALEMODE_NEAREST;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12005. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12006. get: function () {
  12007. return Engine._SCALEMODE_CEILING;
  12008. },
  12009. enumerable: true,
  12010. configurable: true
  12011. });
  12012. Object.defineProperty(Engine, "Version", {
  12013. /**
  12014. * Returns the current version of the framework
  12015. */
  12016. get: function () {
  12017. return "3.3.0-alpha.2";
  12018. },
  12019. enumerable: true,
  12020. configurable: true
  12021. });
  12022. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12023. /**
  12024. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12025. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12026. */
  12027. get: function () {
  12028. return this._vrExclusivePointerMode;
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12034. /**
  12035. * Gets a boolean indicating that the engine supports uniform buffers
  12036. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12037. */
  12038. get: function () {
  12039. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12040. },
  12041. enumerable: true,
  12042. configurable: true
  12043. });
  12044. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12045. /**
  12046. * Gets a boolean indicating that only power of 2 textures are supported
  12047. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12048. */
  12049. get: function () {
  12050. return this._webGLVersion < 2 || this.forcePOTTextures;
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12056. /**
  12057. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12058. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12059. */
  12060. get: function () {
  12061. return this._doNotHandleContextLost;
  12062. },
  12063. set: function (value) {
  12064. this._doNotHandleContextLost = value;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12070. /**
  12071. * Gets the performance monitor attached to this engine
  12072. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12073. */
  12074. get: function () {
  12075. return this._performanceMonitor;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12081. /**
  12082. * Gets the list of texture formats supported
  12083. */
  12084. get: function () {
  12085. return this._texturesSupported;
  12086. },
  12087. enumerable: true,
  12088. configurable: true
  12089. });
  12090. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12091. /**
  12092. * Gets the list of texture formats in use
  12093. */
  12094. get: function () {
  12095. return this._textureFormatInUse;
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(Engine.prototype, "currentViewport", {
  12101. /**
  12102. * Gets the current viewport
  12103. */
  12104. get: function () {
  12105. return this._cachedViewport;
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12111. /**
  12112. * Gets the default empty texture
  12113. */
  12114. get: function () {
  12115. if (!this._emptyTexture) {
  12116. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12117. }
  12118. return this._emptyTexture;
  12119. },
  12120. enumerable: true,
  12121. configurable: true
  12122. });
  12123. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12124. /**
  12125. * Gets the default empty 3D texture
  12126. */
  12127. get: function () {
  12128. if (!this._emptyTexture3D) {
  12129. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12130. }
  12131. return this._emptyTexture3D;
  12132. },
  12133. enumerable: true,
  12134. configurable: true
  12135. });
  12136. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12137. /**
  12138. * Gets the default empty cube texture
  12139. */
  12140. get: function () {
  12141. if (!this._emptyCubeTexture) {
  12142. var faceData = new Uint8Array(4);
  12143. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12144. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12145. }
  12146. return this._emptyCubeTexture;
  12147. },
  12148. enumerable: true,
  12149. configurable: true
  12150. });
  12151. Engine.prototype._rebuildInternalTextures = function () {
  12152. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12153. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12154. var internalTexture = currentState_1[_i];
  12155. internalTexture._rebuild();
  12156. }
  12157. };
  12158. Engine.prototype._rebuildEffects = function () {
  12159. for (var key in this._compiledEffects) {
  12160. var effect = this._compiledEffects[key];
  12161. effect._prepareEffect();
  12162. }
  12163. BABYLON.Effect.ResetCache();
  12164. };
  12165. Engine.prototype._rebuildBuffers = function () {
  12166. // Index / Vertex
  12167. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12168. var scene = _a[_i];
  12169. scene.resetCachedMaterial();
  12170. scene._rebuildGeometries();
  12171. scene._rebuildTextures();
  12172. }
  12173. // Uniforms
  12174. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12175. var uniformBuffer = _c[_b];
  12176. uniformBuffer._rebuild();
  12177. }
  12178. };
  12179. Engine.prototype._initGLContext = function () {
  12180. // Caps
  12181. this._caps = new EngineCapabilities();
  12182. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12183. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12184. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12185. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12186. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12187. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12188. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12189. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12190. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12191. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12192. // Infos
  12193. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12194. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12195. if (rendererInfo != null) {
  12196. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12197. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12198. }
  12199. if (!this._glVendor) {
  12200. this._glVendor = "Unknown vendor";
  12201. }
  12202. if (!this._glRenderer) {
  12203. this._glRenderer = "Unknown renderer";
  12204. }
  12205. // Constants
  12206. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12207. if (this._gl.RGBA16F !== 0x881A) {
  12208. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12209. }
  12210. if (this._gl.RGBA32F !== 0x8814) {
  12211. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12212. }
  12213. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12214. this._gl.DEPTH24_STENCIL8 = 35056;
  12215. }
  12216. // Extensions
  12217. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12218. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12219. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12220. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12221. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12222. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12223. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12224. 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');
  12225. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12226. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12227. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12228. this._caps.highPrecisionShaderSupported = true;
  12229. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12230. if (this._caps.timerQuery) {
  12231. if (this._webGLVersion === 1) {
  12232. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12233. }
  12234. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12235. }
  12236. // Checks if some of the format renders first to allow the use of webgl inspector.
  12237. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12238. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12239. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12240. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12241. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12242. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12243. if (this._webGLVersion > 1) {
  12244. this._gl.HALF_FLOAT_OES = 0x140B;
  12245. }
  12246. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12247. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12248. // Draw buffers
  12249. if (this._webGLVersion > 1) {
  12250. this._caps.drawBuffersExtension = true;
  12251. }
  12252. else {
  12253. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12254. if (drawBuffersExtension !== null) {
  12255. this._caps.drawBuffersExtension = true;
  12256. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12257. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12258. for (var i = 0; i < 16; i++) {
  12259. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12260. }
  12261. }
  12262. else {
  12263. this._caps.drawBuffersExtension = false;
  12264. }
  12265. }
  12266. // Depth Texture
  12267. if (this._webGLVersion > 1) {
  12268. this._caps.depthTextureExtension = true;
  12269. }
  12270. else {
  12271. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12272. if (depthTextureExtension != null) {
  12273. this._caps.depthTextureExtension = true;
  12274. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12275. }
  12276. }
  12277. // Vertex array object
  12278. if (this._webGLVersion > 1) {
  12279. this._caps.vertexArrayObject = true;
  12280. }
  12281. else {
  12282. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12283. if (vertexArrayObjectExtension != null) {
  12284. this._caps.vertexArrayObject = true;
  12285. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12286. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12287. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12288. }
  12289. else {
  12290. this._caps.vertexArrayObject = false;
  12291. }
  12292. }
  12293. // Instances count
  12294. if (this._webGLVersion > 1) {
  12295. this._caps.instancedArrays = true;
  12296. }
  12297. else {
  12298. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12299. if (instanceExtension != null) {
  12300. this._caps.instancedArrays = true;
  12301. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12302. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12303. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12304. }
  12305. else {
  12306. this._caps.instancedArrays = false;
  12307. }
  12308. }
  12309. // Intelligently add supported compressed formats in order to check for.
  12310. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12311. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12312. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12313. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12314. if (this._caps.astc)
  12315. this.texturesSupported.push('-astc.ktx');
  12316. if (this._caps.s3tc)
  12317. this.texturesSupported.push('-dxt.ktx');
  12318. if (this._caps.pvrtc)
  12319. this.texturesSupported.push('-pvrtc.ktx');
  12320. if (this._caps.etc2)
  12321. this.texturesSupported.push('-etc2.ktx');
  12322. if (this._caps.etc1)
  12323. this.texturesSupported.push('-etc1.ktx');
  12324. if (this._gl.getShaderPrecisionFormat) {
  12325. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12326. if (highp) {
  12327. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12328. }
  12329. }
  12330. // Depth buffer
  12331. this.setDepthBuffer(true);
  12332. this.setDepthFunctionToLessOrEqual();
  12333. this.setDepthWrite(true);
  12334. // Texture maps
  12335. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12336. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12337. this._nextFreeTextureSlots.push(slot);
  12338. }
  12339. };
  12340. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12341. /**
  12342. * Gets version of the current webGL context
  12343. */
  12344. get: function () {
  12345. return this._webGLVersion;
  12346. },
  12347. enumerable: true,
  12348. configurable: true
  12349. });
  12350. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12351. /**
  12352. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12353. */
  12354. get: function () {
  12355. return this._isStencilEnable;
  12356. },
  12357. enumerable: true,
  12358. configurable: true
  12359. });
  12360. Engine.prototype._prepareWorkingCanvas = function () {
  12361. if (this._workingCanvas) {
  12362. return;
  12363. }
  12364. this._workingCanvas = document.createElement("canvas");
  12365. var context = this._workingCanvas.getContext("2d");
  12366. if (context) {
  12367. this._workingContext = context;
  12368. }
  12369. };
  12370. /**
  12371. * Reset the texture cache to empty state
  12372. */
  12373. Engine.prototype.resetTextureCache = function () {
  12374. for (var key in this._boundTexturesCache) {
  12375. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12376. continue;
  12377. }
  12378. var boundTexture = this._boundTexturesCache[key];
  12379. if (boundTexture) {
  12380. this._removeDesignatedSlot(boundTexture);
  12381. }
  12382. this._boundTexturesCache[key] = null;
  12383. }
  12384. if (!this.disableTextureBindingOptimization) {
  12385. this._nextFreeTextureSlots = [];
  12386. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12387. this._nextFreeTextureSlots.push(slot);
  12388. }
  12389. }
  12390. this._currentTextureChannel = -1;
  12391. };
  12392. /**
  12393. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12394. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12395. * @returns true if engine is in deterministic lock step mode
  12396. */
  12397. Engine.prototype.isDeterministicLockStep = function () {
  12398. return this._deterministicLockstep;
  12399. };
  12400. /**
  12401. * Gets the max steps when engine is running in deterministic lock step
  12402. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12403. * @returns the max steps
  12404. */
  12405. Engine.prototype.getLockstepMaxSteps = function () {
  12406. return this._lockstepMaxSteps;
  12407. };
  12408. /**
  12409. * Gets an object containing information about the current webGL context
  12410. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12411. */
  12412. Engine.prototype.getGlInfo = function () {
  12413. return {
  12414. vendor: this._glVendor,
  12415. renderer: this._glRenderer,
  12416. version: this._glVersion
  12417. };
  12418. };
  12419. /**
  12420. * Gets current aspect ratio
  12421. * @param camera defines the camera to use to get the aspect ratio
  12422. * @param useScreen defines if screen size must be used (or the current render target if any)
  12423. * @returns a number defining the aspect ratio
  12424. */
  12425. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12426. if (useScreen === void 0) { useScreen = false; }
  12427. var viewport = camera.viewport;
  12428. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12429. };
  12430. /**
  12431. * Gets current screen aspect ratio
  12432. * @returns a number defining the aspect ratio
  12433. */
  12434. Engine.prototype.getScreenAspectRatio = function () {
  12435. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12436. };
  12437. /**
  12438. * Gets the current render width
  12439. * @param useScreen defines if screen size must be used (or the current render target if any)
  12440. * @returns a number defining the current render width
  12441. */
  12442. Engine.prototype.getRenderWidth = function (useScreen) {
  12443. if (useScreen === void 0) { useScreen = false; }
  12444. if (!useScreen && this._currentRenderTarget) {
  12445. return this._currentRenderTarget.width;
  12446. }
  12447. return this._gl.drawingBufferWidth;
  12448. };
  12449. /**
  12450. * Gets the current render height
  12451. * @param useScreen defines if screen size must be used (or the current render target if any)
  12452. * @returns a number defining the current render height
  12453. */
  12454. Engine.prototype.getRenderHeight = function (useScreen) {
  12455. if (useScreen === void 0) { useScreen = false; }
  12456. if (!useScreen && this._currentRenderTarget) {
  12457. return this._currentRenderTarget.height;
  12458. }
  12459. return this._gl.drawingBufferHeight;
  12460. };
  12461. /**
  12462. * Gets the HTML canvas attached with the current webGL context
  12463. * @returns a HTML canvas
  12464. */
  12465. Engine.prototype.getRenderingCanvas = function () {
  12466. return this._renderingCanvas;
  12467. };
  12468. /**
  12469. * Gets the client rect of the HTML canvas attached with the current webGL context
  12470. * @returns a client rectanglee
  12471. */
  12472. Engine.prototype.getRenderingCanvasClientRect = function () {
  12473. if (!this._renderingCanvas) {
  12474. return null;
  12475. }
  12476. return this._renderingCanvas.getBoundingClientRect();
  12477. };
  12478. /**
  12479. * Defines the hardware scaling level.
  12480. * By default the hardware scaling level is computed from the window device ratio.
  12481. * 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.
  12482. * @param level defines the level to use
  12483. */
  12484. Engine.prototype.setHardwareScalingLevel = function (level) {
  12485. this._hardwareScalingLevel = level;
  12486. this.resize();
  12487. };
  12488. /**
  12489. * Gets the current hardware scaling level.
  12490. * By default the hardware scaling level is computed from the window device ratio.
  12491. * 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.
  12492. * @returns a number indicating the current hardware scaling level
  12493. */
  12494. Engine.prototype.getHardwareScalingLevel = function () {
  12495. return this._hardwareScalingLevel;
  12496. };
  12497. /**
  12498. * Gets the list of loaded textures
  12499. * @returns an array containing all loaded textures
  12500. */
  12501. Engine.prototype.getLoadedTexturesCache = function () {
  12502. return this._internalTexturesCache;
  12503. };
  12504. /**
  12505. * Gets the object containing all engine capabilities
  12506. * @returns the EngineCapabilities object
  12507. */
  12508. Engine.prototype.getCaps = function () {
  12509. return this._caps;
  12510. };
  12511. Object.defineProperty(Engine.prototype, "drawCalls", {
  12512. /** @hidden */
  12513. get: function () {
  12514. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12515. return 0;
  12516. },
  12517. enumerable: true,
  12518. configurable: true
  12519. });
  12520. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12521. /** @hidden */
  12522. get: function () {
  12523. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12524. return null;
  12525. },
  12526. enumerable: true,
  12527. configurable: true
  12528. });
  12529. /**
  12530. * Gets the current depth function
  12531. * @returns a number defining the depth function
  12532. */
  12533. Engine.prototype.getDepthFunction = function () {
  12534. return this._depthCullingState.depthFunc;
  12535. };
  12536. /**
  12537. * Sets the current depth function
  12538. * @param depthFunc defines the function to use
  12539. */
  12540. Engine.prototype.setDepthFunction = function (depthFunc) {
  12541. this._depthCullingState.depthFunc = depthFunc;
  12542. };
  12543. /**
  12544. * Sets the current depth function to GREATER
  12545. */
  12546. Engine.prototype.setDepthFunctionToGreater = function () {
  12547. this._depthCullingState.depthFunc = this._gl.GREATER;
  12548. };
  12549. /**
  12550. * Sets the current depth function to GEQUAL
  12551. */
  12552. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12553. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12554. };
  12555. /**
  12556. * Sets the current depth function to LESS
  12557. */
  12558. Engine.prototype.setDepthFunctionToLess = function () {
  12559. this._depthCullingState.depthFunc = this._gl.LESS;
  12560. };
  12561. /**
  12562. * Sets the current depth function to LEQUAL
  12563. */
  12564. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12565. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12566. };
  12567. /**
  12568. * Gets a boolean indicating if stencil buffer is enabled
  12569. * @returns the current stencil buffer state
  12570. */
  12571. Engine.prototype.getStencilBuffer = function () {
  12572. return this._stencilState.stencilTest;
  12573. };
  12574. /**
  12575. * Enable or disable the stencil buffer
  12576. * @param enable defines if the stencil buffer must be enabled or disabled
  12577. */
  12578. Engine.prototype.setStencilBuffer = function (enable) {
  12579. this._stencilState.stencilTest = enable;
  12580. };
  12581. /**
  12582. * Gets the current stencil mask
  12583. * @returns a number defining the new stencil mask to use
  12584. */
  12585. Engine.prototype.getStencilMask = function () {
  12586. return this._stencilState.stencilMask;
  12587. };
  12588. /**
  12589. * Sets the current stencil mask
  12590. * @param mask defines the new stencil mask to use
  12591. */
  12592. Engine.prototype.setStencilMask = function (mask) {
  12593. this._stencilState.stencilMask = mask;
  12594. };
  12595. /**
  12596. * Gets the current stencil function
  12597. * @returns a number defining the stencil function to use
  12598. */
  12599. Engine.prototype.getStencilFunction = function () {
  12600. return this._stencilState.stencilFunc;
  12601. };
  12602. /**
  12603. * Gets the current stencil reference value
  12604. * @returns a number defining the stencil reference value to use
  12605. */
  12606. Engine.prototype.getStencilFunctionReference = function () {
  12607. return this._stencilState.stencilFuncRef;
  12608. };
  12609. /**
  12610. * Gets the current stencil mask
  12611. * @returns a number defining the stencil mask to use
  12612. */
  12613. Engine.prototype.getStencilFunctionMask = function () {
  12614. return this._stencilState.stencilFuncMask;
  12615. };
  12616. /**
  12617. * Sets the current stencil function
  12618. * @param stencilFunc defines the new stencil function to use
  12619. */
  12620. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12621. this._stencilState.stencilFunc = stencilFunc;
  12622. };
  12623. /**
  12624. * Sets the current stencil reference
  12625. * @param reference defines the new stencil reference to use
  12626. */
  12627. Engine.prototype.setStencilFunctionReference = function (reference) {
  12628. this._stencilState.stencilFuncRef = reference;
  12629. };
  12630. /**
  12631. * Sets the current stencil mask
  12632. * @param mask defines the new stencil mask to use
  12633. */
  12634. Engine.prototype.setStencilFunctionMask = function (mask) {
  12635. this._stencilState.stencilFuncMask = mask;
  12636. };
  12637. /**
  12638. * Gets the current stencil operation when stencil fails
  12639. * @returns a number defining stencil operation to use when stencil fails
  12640. */
  12641. Engine.prototype.getStencilOperationFail = function () {
  12642. return this._stencilState.stencilOpStencilFail;
  12643. };
  12644. /**
  12645. * Gets the current stencil operation when depth fails
  12646. * @returns a number defining stencil operation to use when depth fails
  12647. */
  12648. Engine.prototype.getStencilOperationDepthFail = function () {
  12649. return this._stencilState.stencilOpDepthFail;
  12650. };
  12651. /**
  12652. * Gets the current stencil operation when stencil passes
  12653. * @returns a number defining stencil operation to use when stencil passes
  12654. */
  12655. Engine.prototype.getStencilOperationPass = function () {
  12656. return this._stencilState.stencilOpStencilDepthPass;
  12657. };
  12658. /**
  12659. * Sets the stencil operation to use when stencil fails
  12660. * @param operation defines the stencil operation to use when stencil fails
  12661. */
  12662. Engine.prototype.setStencilOperationFail = function (operation) {
  12663. this._stencilState.stencilOpStencilFail = operation;
  12664. };
  12665. /**
  12666. * Sets the stencil operation to use when depth fails
  12667. * @param operation defines the stencil operation to use when depth fails
  12668. */
  12669. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12670. this._stencilState.stencilOpDepthFail = operation;
  12671. };
  12672. /**
  12673. * Sets the stencil operation to use when stencil passes
  12674. * @param operation defines the stencil operation to use when stencil passes
  12675. */
  12676. Engine.prototype.setStencilOperationPass = function (operation) {
  12677. this._stencilState.stencilOpStencilDepthPass = operation;
  12678. };
  12679. /**
  12680. * Sets a boolean indicating if the dithering state is enabled or disabled
  12681. * @param value defines the dithering state
  12682. */
  12683. Engine.prototype.setDitheringState = function (value) {
  12684. if (value) {
  12685. this._gl.enable(this._gl.DITHER);
  12686. }
  12687. else {
  12688. this._gl.disable(this._gl.DITHER);
  12689. }
  12690. };
  12691. /**
  12692. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12693. * @param value defines the rasterizer state
  12694. */
  12695. Engine.prototype.setRasterizerState = function (value) {
  12696. if (value) {
  12697. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12698. }
  12699. else {
  12700. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12701. }
  12702. };
  12703. /**
  12704. * stop executing a render loop function and remove it from the execution array
  12705. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12706. */
  12707. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12708. if (!renderFunction) {
  12709. this._activeRenderLoops = [];
  12710. return;
  12711. }
  12712. var index = this._activeRenderLoops.indexOf(renderFunction);
  12713. if (index >= 0) {
  12714. this._activeRenderLoops.splice(index, 1);
  12715. }
  12716. };
  12717. /** @hidden */
  12718. Engine.prototype._renderLoop = function () {
  12719. if (!this._contextWasLost) {
  12720. var shouldRender = true;
  12721. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12722. shouldRender = false;
  12723. }
  12724. if (shouldRender) {
  12725. // Start new frame
  12726. this.beginFrame();
  12727. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12728. var renderFunction = this._activeRenderLoops[index];
  12729. renderFunction();
  12730. }
  12731. // Present
  12732. this.endFrame();
  12733. }
  12734. }
  12735. if (this._activeRenderLoops.length > 0) {
  12736. // Register new frame
  12737. var requester = null;
  12738. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12739. requester = this._vrDisplay;
  12740. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12741. }
  12742. else {
  12743. this._renderingQueueLaunched = false;
  12744. }
  12745. };
  12746. /**
  12747. * Register and execute a render loop. The engine can have more than one render function
  12748. * @param renderFunction defines the function to continuously execute
  12749. */
  12750. Engine.prototype.runRenderLoop = function (renderFunction) {
  12751. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12752. return;
  12753. }
  12754. this._activeRenderLoops.push(renderFunction);
  12755. if (!this._renderingQueueLaunched) {
  12756. this._renderingQueueLaunched = true;
  12757. this._bindedRenderFunction = this._renderLoop.bind(this);
  12758. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12759. }
  12760. };
  12761. /**
  12762. * Toggle full screen mode
  12763. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12764. * @param options defines an option object to be sent to the requestFullscreen function
  12765. */
  12766. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12767. if (this.isFullscreen) {
  12768. BABYLON.Tools.ExitFullscreen();
  12769. }
  12770. else {
  12771. this._pointerLockRequested = requestPointerLock;
  12772. if (this._renderingCanvas) {
  12773. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12774. }
  12775. }
  12776. };
  12777. /**
  12778. * Clear the current render buffer or the current render target (if any is set up)
  12779. * @param color defines the color to use
  12780. * @param backBuffer defines if the back buffer must be cleared
  12781. * @param depth defines if the depth buffer must be cleared
  12782. * @param stencil defines if the stencil buffer must be cleared
  12783. */
  12784. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12785. if (stencil === void 0) { stencil = false; }
  12786. this.applyStates();
  12787. var mode = 0;
  12788. if (backBuffer && color) {
  12789. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12790. mode |= this._gl.COLOR_BUFFER_BIT;
  12791. }
  12792. if (depth) {
  12793. this._gl.clearDepth(1.0);
  12794. mode |= this._gl.DEPTH_BUFFER_BIT;
  12795. }
  12796. if (stencil) {
  12797. this._gl.clearStencil(0);
  12798. mode |= this._gl.STENCIL_BUFFER_BIT;
  12799. }
  12800. this._gl.clear(mode);
  12801. };
  12802. /**
  12803. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12804. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12805. * @param y defines the y-coordinate of the corner of the clear rectangle
  12806. * @param width defines the width of the clear rectangle
  12807. * @param height defines the height of the clear rectangle
  12808. * @param clearColor defines the clear color
  12809. */
  12810. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12811. var gl = this._gl;
  12812. // Save state
  12813. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12814. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12815. // Change state
  12816. gl.enable(gl.SCISSOR_TEST);
  12817. gl.scissor(x, y, width, height);
  12818. // Clear
  12819. this.clear(clearColor, true, true, true);
  12820. // Restore state
  12821. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12822. if (curScissor === true) {
  12823. gl.enable(gl.SCISSOR_TEST);
  12824. }
  12825. else {
  12826. gl.disable(gl.SCISSOR_TEST);
  12827. }
  12828. };
  12829. /**
  12830. * Set the WebGL's viewport
  12831. * @param viewport defines the viewport element to be used
  12832. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12833. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12834. */
  12835. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12836. var width = requiredWidth || this.getRenderWidth();
  12837. var height = requiredHeight || this.getRenderHeight();
  12838. var x = viewport.x || 0;
  12839. var y = viewport.y || 0;
  12840. this._cachedViewport = viewport;
  12841. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12842. };
  12843. /**
  12844. * Directly set the WebGL Viewport
  12845. * @param x defines the x coordinate of the viewport (in screen space)
  12846. * @param y defines the y coordinate of the viewport (in screen space)
  12847. * @param width defines the width of the viewport (in screen space)
  12848. * @param height defines the height of the viewport (in screen space)
  12849. * @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
  12850. */
  12851. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12852. var currentViewport = this._cachedViewport;
  12853. this._cachedViewport = null;
  12854. this._gl.viewport(x, y, width, height);
  12855. return currentViewport;
  12856. };
  12857. /**
  12858. * Begin a new frame
  12859. */
  12860. Engine.prototype.beginFrame = function () {
  12861. this.onBeginFrameObservable.notifyObservers(this);
  12862. this._measureFps();
  12863. };
  12864. /**
  12865. * Enf the current frame
  12866. */
  12867. Engine.prototype.endFrame = function () {
  12868. // Force a flush in case we are using a bad OS.
  12869. if (this._badOS) {
  12870. this.flushFramebuffer();
  12871. }
  12872. // Submit frame to the vr device, if enabled
  12873. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12874. // TODO: We should only submit the frame if we read frameData successfully.
  12875. this._vrDisplay.submitFrame();
  12876. }
  12877. this.onEndFrameObservable.notifyObservers(this);
  12878. };
  12879. /**
  12880. * Resize the view according to the canvas' size
  12881. */
  12882. Engine.prototype.resize = function () {
  12883. // We're not resizing the size of the canvas while in VR mode & presenting
  12884. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12885. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12886. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12887. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12888. }
  12889. };
  12890. /**
  12891. * Force a specific size of the canvas
  12892. * @param width defines the new canvas' width
  12893. * @param height defines the new canvas' height
  12894. */
  12895. Engine.prototype.setSize = function (width, height) {
  12896. if (!this._renderingCanvas) {
  12897. return;
  12898. }
  12899. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12900. return;
  12901. }
  12902. this._renderingCanvas.width = width;
  12903. this._renderingCanvas.height = height;
  12904. for (var index = 0; index < this.scenes.length; index++) {
  12905. var scene = this.scenes[index];
  12906. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12907. var cam = scene.cameras[camIndex];
  12908. cam._currentRenderId = 0;
  12909. }
  12910. }
  12911. if (this.onResizeObservable.hasObservers) {
  12912. this.onResizeObservable.notifyObservers(this);
  12913. }
  12914. };
  12915. // WebVR functions
  12916. /**
  12917. * Gets a boolean indicating if a webVR device was detected
  12918. * @returns true if a webVR device was detected
  12919. */
  12920. Engine.prototype.isVRDevicePresent = function () {
  12921. return !!this._vrDisplay;
  12922. };
  12923. /**
  12924. * Gets the current webVR device
  12925. * @returns the current webVR device (or null)
  12926. */
  12927. Engine.prototype.getVRDevice = function () {
  12928. return this._vrDisplay;
  12929. };
  12930. /**
  12931. * Initializes a webVR display and starts listening to display change events
  12932. * The onVRDisplayChangedObservable will be notified upon these changes
  12933. * @returns The onVRDisplayChangedObservable
  12934. */
  12935. Engine.prototype.initWebVR = function () {
  12936. this.initWebVRAsync();
  12937. return this.onVRDisplayChangedObservable;
  12938. };
  12939. /**
  12940. * Initializes a webVR display and starts listening to display change events
  12941. * The onVRDisplayChangedObservable will be notified upon these changes
  12942. * @returns A promise containing a VRDisplay and if vr is supported
  12943. */
  12944. Engine.prototype.initWebVRAsync = function () {
  12945. var _this = this;
  12946. var notifyObservers = function () {
  12947. var eventArgs = {
  12948. vrDisplay: _this._vrDisplay,
  12949. vrSupported: _this._vrSupported
  12950. };
  12951. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12952. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12953. };
  12954. if (!this._onVrDisplayConnect) {
  12955. this._onVrDisplayConnect = function (event) {
  12956. _this._vrDisplay = event.display;
  12957. notifyObservers();
  12958. };
  12959. this._onVrDisplayDisconnect = function () {
  12960. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12961. _this._vrDisplay = undefined;
  12962. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12963. notifyObservers();
  12964. };
  12965. this._onVrDisplayPresentChange = function () {
  12966. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12967. };
  12968. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12969. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12970. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12971. }
  12972. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12973. this._webVRInitPromise.then(notifyObservers);
  12974. return this._webVRInitPromise;
  12975. };
  12976. /**
  12977. * Call this function to switch to webVR mode
  12978. * Will do nothing if webVR is not supported or if there is no webVR device
  12979. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12980. */
  12981. Engine.prototype.enableVR = function () {
  12982. var _this = this;
  12983. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12984. var onResolved = function () {
  12985. _this.onVRRequestPresentComplete.notifyObservers(true);
  12986. _this._onVRFullScreenTriggered();
  12987. };
  12988. var onRejected = function () {
  12989. _this.onVRRequestPresentComplete.notifyObservers(false);
  12990. };
  12991. this.onVRRequestPresentStart.notifyObservers(this);
  12992. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12993. }
  12994. };
  12995. /**
  12996. * Call this function to leave webVR mode
  12997. * Will do nothing if webVR is not supported or if there is no webVR device
  12998. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12999. */
  13000. Engine.prototype.disableVR = function () {
  13001. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13002. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13003. }
  13004. };
  13005. Engine.prototype._getVRDisplaysAsync = function () {
  13006. var _this = this;
  13007. return new Promise(function (res, rej) {
  13008. if (navigator.getVRDisplays) {
  13009. navigator.getVRDisplays().then(function (devices) {
  13010. _this._vrSupported = true;
  13011. // note that devices may actually be an empty array. This is fine;
  13012. // we expect this._vrDisplay to be undefined in this case.
  13013. _this._vrDisplay = devices[0];
  13014. res({
  13015. vrDisplay: _this._vrDisplay,
  13016. vrSupported: _this._vrSupported
  13017. });
  13018. });
  13019. }
  13020. else {
  13021. _this._vrDisplay = undefined;
  13022. _this._vrSupported = false;
  13023. res({
  13024. vrDisplay: _this._vrDisplay,
  13025. vrSupported: _this._vrSupported
  13026. });
  13027. }
  13028. });
  13029. };
  13030. /**
  13031. * Binds the frame buffer to the specified texture.
  13032. * @param texture The texture to render to or null for the default canvas
  13033. * @param faceIndex The face of the texture to render to in case of cube texture
  13034. * @param requiredWidth The width of the target to render to
  13035. * @param requiredHeight The height of the target to render to
  13036. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13037. * @param depthStencilTexture The depth stencil texture to use to render
  13038. */
  13039. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13040. if (this._currentRenderTarget) {
  13041. this.unBindFramebuffer(this._currentRenderTarget);
  13042. }
  13043. this._currentRenderTarget = texture;
  13044. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13045. var gl = this._gl;
  13046. if (texture.isCube) {
  13047. if (faceIndex === undefined) {
  13048. faceIndex = 0;
  13049. }
  13050. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13051. if (depthStencilTexture) {
  13052. if (depthStencilTexture._generateStencilBuffer) {
  13053. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13054. }
  13055. else {
  13056. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13057. }
  13058. }
  13059. }
  13060. if (this._cachedViewport && !forceFullscreenViewport) {
  13061. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13062. }
  13063. else {
  13064. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13065. }
  13066. this.wipeCaches();
  13067. };
  13068. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13069. if (this._currentFramebuffer !== framebuffer) {
  13070. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13071. this._currentFramebuffer = framebuffer;
  13072. }
  13073. };
  13074. /**
  13075. * Unbind the current render target texture from the webGL context
  13076. * @param texture defines the render target texture to unbind
  13077. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13078. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13079. */
  13080. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13081. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13082. this._currentRenderTarget = null;
  13083. // If MSAA, we need to bitblt back to main texture
  13084. var gl = this._gl;
  13085. if (texture._MSAAFramebuffer) {
  13086. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13087. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13088. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13089. }
  13090. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13091. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13092. gl.generateMipmap(gl.TEXTURE_2D);
  13093. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13094. }
  13095. if (onBeforeUnbind) {
  13096. if (texture._MSAAFramebuffer) {
  13097. // Bind the correct framebuffer
  13098. this.bindUnboundFramebuffer(texture._framebuffer);
  13099. }
  13100. onBeforeUnbind();
  13101. }
  13102. this.bindUnboundFramebuffer(null);
  13103. };
  13104. /**
  13105. * Unbind a list of render target textures from the webGL context
  13106. * This is used only when drawBuffer extension or webGL2 are active
  13107. * @param textures defines the render target textures to unbind
  13108. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13109. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13110. */
  13111. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13112. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13113. this._currentRenderTarget = null;
  13114. // If MSAA, we need to bitblt back to main texture
  13115. var gl = this._gl;
  13116. if (textures[0]._MSAAFramebuffer) {
  13117. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13118. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13119. var attachments = textures[0]._attachments;
  13120. if (!attachments) {
  13121. attachments = new Array(textures.length);
  13122. textures[0]._attachments = attachments;
  13123. }
  13124. for (var i = 0; i < textures.length; i++) {
  13125. var texture = textures[i];
  13126. for (var j = 0; j < attachments.length; j++) {
  13127. attachments[j] = gl.NONE;
  13128. }
  13129. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13130. gl.readBuffer(attachments[i]);
  13131. gl.drawBuffers(attachments);
  13132. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13133. }
  13134. for (var i = 0; i < attachments.length; i++) {
  13135. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13136. }
  13137. gl.drawBuffers(attachments);
  13138. }
  13139. for (var i = 0; i < textures.length; i++) {
  13140. var texture = textures[i];
  13141. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13142. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13143. gl.generateMipmap(gl.TEXTURE_2D);
  13144. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13145. }
  13146. }
  13147. if (onBeforeUnbind) {
  13148. if (textures[0]._MSAAFramebuffer) {
  13149. // Bind the correct framebuffer
  13150. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13151. }
  13152. onBeforeUnbind();
  13153. }
  13154. this.bindUnboundFramebuffer(null);
  13155. };
  13156. /**
  13157. * Force the mipmap generation for the given render target texture
  13158. * @param texture defines the render target texture to use
  13159. */
  13160. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13161. if (texture.generateMipMaps) {
  13162. var gl = this._gl;
  13163. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13164. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13165. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13166. }
  13167. };
  13168. /**
  13169. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13170. */
  13171. Engine.prototype.flushFramebuffer = function () {
  13172. this._gl.flush();
  13173. };
  13174. /**
  13175. * Unbind the current render target and bind the default framebuffer
  13176. */
  13177. Engine.prototype.restoreDefaultFramebuffer = function () {
  13178. if (this._currentRenderTarget) {
  13179. this.unBindFramebuffer(this._currentRenderTarget);
  13180. }
  13181. else {
  13182. this.bindUnboundFramebuffer(null);
  13183. }
  13184. if (this._cachedViewport) {
  13185. this.setViewport(this._cachedViewport);
  13186. }
  13187. this.wipeCaches();
  13188. };
  13189. // UBOs
  13190. /**
  13191. * Create an uniform buffer
  13192. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13193. * @param elements defines the content of the uniform buffer
  13194. * @returns the webGL uniform buffer
  13195. */
  13196. Engine.prototype.createUniformBuffer = function (elements) {
  13197. var ubo = this._gl.createBuffer();
  13198. if (!ubo) {
  13199. throw new Error("Unable to create uniform buffer");
  13200. }
  13201. this.bindUniformBuffer(ubo);
  13202. if (elements instanceof Float32Array) {
  13203. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13204. }
  13205. else {
  13206. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13207. }
  13208. this.bindUniformBuffer(null);
  13209. ubo.references = 1;
  13210. return ubo;
  13211. };
  13212. /**
  13213. * Create a dynamic uniform buffer
  13214. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13215. * @param elements defines the content of the uniform buffer
  13216. * @returns the webGL uniform buffer
  13217. */
  13218. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13219. var ubo = this._gl.createBuffer();
  13220. if (!ubo) {
  13221. throw new Error("Unable to create dynamic uniform buffer");
  13222. }
  13223. this.bindUniformBuffer(ubo);
  13224. if (elements instanceof Float32Array) {
  13225. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13226. }
  13227. else {
  13228. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13229. }
  13230. this.bindUniformBuffer(null);
  13231. ubo.references = 1;
  13232. return ubo;
  13233. };
  13234. /**
  13235. * Update an existing uniform buffer
  13236. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13237. * @param uniformBuffer defines the target uniform buffer
  13238. * @param elements defines the content to update
  13239. * @param offset defines the offset in the uniform buffer where update should start
  13240. * @param count defines the size of the data to update
  13241. */
  13242. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13243. this.bindUniformBuffer(uniformBuffer);
  13244. if (offset === undefined) {
  13245. offset = 0;
  13246. }
  13247. if (count === undefined) {
  13248. if (elements instanceof Float32Array) {
  13249. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13250. }
  13251. else {
  13252. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13253. }
  13254. }
  13255. else {
  13256. if (elements instanceof Float32Array) {
  13257. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13258. }
  13259. else {
  13260. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13261. }
  13262. }
  13263. this.bindUniformBuffer(null);
  13264. };
  13265. // VBOs
  13266. Engine.prototype._resetVertexBufferBinding = function () {
  13267. this.bindArrayBuffer(null);
  13268. this._cachedVertexBuffers = null;
  13269. };
  13270. /**
  13271. * Creates a vertex buffer
  13272. * @param data the data for the vertex buffer
  13273. * @returns the new WebGL static buffer
  13274. */
  13275. Engine.prototype.createVertexBuffer = function (data) {
  13276. var vbo = this._gl.createBuffer();
  13277. if (!vbo) {
  13278. throw new Error("Unable to create vertex buffer");
  13279. }
  13280. this.bindArrayBuffer(vbo);
  13281. if (data instanceof Array) {
  13282. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13283. }
  13284. else {
  13285. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13286. }
  13287. this._resetVertexBufferBinding();
  13288. vbo.references = 1;
  13289. return vbo;
  13290. };
  13291. /**
  13292. * Creates a dynamic vertex buffer
  13293. * @param data the data for the dynamic vertex buffer
  13294. * @returns the new WebGL dynamic buffer
  13295. */
  13296. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13297. var vbo = this._gl.createBuffer();
  13298. if (!vbo) {
  13299. throw new Error("Unable to create dynamic vertex buffer");
  13300. }
  13301. this.bindArrayBuffer(vbo);
  13302. if (data instanceof Array) {
  13303. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13304. }
  13305. else {
  13306. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13307. }
  13308. this._resetVertexBufferBinding();
  13309. vbo.references = 1;
  13310. return vbo;
  13311. };
  13312. /**
  13313. * Update a dynamic index buffer
  13314. * @param indexBuffer defines the target index buffer
  13315. * @param indices defines the data to update
  13316. * @param offset defines the offset in the target index buffer where update should start
  13317. */
  13318. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13319. if (offset === void 0) { offset = 0; }
  13320. // Force cache update
  13321. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13322. this.bindIndexBuffer(indexBuffer);
  13323. var arrayBuffer;
  13324. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13325. arrayBuffer = indices;
  13326. }
  13327. else {
  13328. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13329. }
  13330. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13331. this._resetIndexBufferBinding();
  13332. };
  13333. /**
  13334. * Updates a dynamic vertex buffer.
  13335. * @param vertexBuffer the vertex buffer to update
  13336. * @param data the data used to update the vertex buffer
  13337. * @param byteOffset the byte offset of the data
  13338. * @param byteLength the byte length of the data
  13339. */
  13340. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13341. this.bindArrayBuffer(vertexBuffer);
  13342. if (byteOffset === undefined) {
  13343. byteOffset = 0;
  13344. }
  13345. if (byteLength === undefined) {
  13346. if (data instanceof Array) {
  13347. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13348. }
  13349. else {
  13350. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13351. }
  13352. }
  13353. else {
  13354. if (data instanceof Array) {
  13355. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13356. }
  13357. else {
  13358. if (data instanceof ArrayBuffer) {
  13359. data = new Uint8Array(data, byteOffset, byteLength);
  13360. }
  13361. else {
  13362. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13363. }
  13364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13365. }
  13366. }
  13367. this._resetVertexBufferBinding();
  13368. };
  13369. Engine.prototype._resetIndexBufferBinding = function () {
  13370. this.bindIndexBuffer(null);
  13371. this._cachedIndexBuffer = null;
  13372. };
  13373. /**
  13374. * Creates a new index buffer
  13375. * @param indices defines the content of the index buffer
  13376. * @param updatable defines if the index buffer must be updatable
  13377. * @returns a new webGL buffer
  13378. */
  13379. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13380. var vbo = this._gl.createBuffer();
  13381. if (!vbo) {
  13382. throw new Error("Unable to create index buffer");
  13383. }
  13384. this.bindIndexBuffer(vbo);
  13385. // Check for 32 bits indices
  13386. var arrayBuffer;
  13387. var need32Bits = false;
  13388. if (indices instanceof Uint16Array) {
  13389. arrayBuffer = indices;
  13390. }
  13391. else {
  13392. //check 32 bit support
  13393. if (this._caps.uintIndices) {
  13394. if (indices instanceof Uint32Array) {
  13395. arrayBuffer = indices;
  13396. need32Bits = true;
  13397. }
  13398. else {
  13399. //number[] or Int32Array, check if 32 bit is necessary
  13400. for (var index = 0; index < indices.length; index++) {
  13401. if (indices[index] > 65535) {
  13402. need32Bits = true;
  13403. break;
  13404. }
  13405. }
  13406. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13407. }
  13408. }
  13409. else {
  13410. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13411. arrayBuffer = new Uint16Array(indices);
  13412. }
  13413. }
  13414. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13415. this._resetIndexBufferBinding();
  13416. vbo.references = 1;
  13417. vbo.is32Bits = need32Bits;
  13418. return vbo;
  13419. };
  13420. /**
  13421. * Bind a webGL buffer to the webGL context
  13422. * @param buffer defines the buffer to bind
  13423. */
  13424. Engine.prototype.bindArrayBuffer = function (buffer) {
  13425. if (!this._vaoRecordInProgress) {
  13426. this._unbindVertexArrayObject();
  13427. }
  13428. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13429. };
  13430. /**
  13431. * Bind an uniform buffer to the current webGL context
  13432. * @param buffer defines the buffer to bind
  13433. */
  13434. Engine.prototype.bindUniformBuffer = function (buffer) {
  13435. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13436. };
  13437. /**
  13438. * Bind a buffer to the current webGL context at a given location
  13439. * @param buffer defines the buffer to bind
  13440. * @param location defines the index where to bind the buffer
  13441. */
  13442. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13443. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13444. };
  13445. /**
  13446. * Bind a specific block at a given index in a specific shader program
  13447. * @param shaderProgram defines the shader program
  13448. * @param blockName defines the block name
  13449. * @param index defines the index where to bind the block
  13450. */
  13451. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13452. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13453. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13454. };
  13455. ;
  13456. Engine.prototype.bindIndexBuffer = function (buffer) {
  13457. if (!this._vaoRecordInProgress) {
  13458. this._unbindVertexArrayObject();
  13459. }
  13460. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13461. };
  13462. Engine.prototype.bindBuffer = function (buffer, target) {
  13463. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13464. this._gl.bindBuffer(target, buffer);
  13465. this._currentBoundBuffer[target] = buffer;
  13466. }
  13467. };
  13468. /**
  13469. * update the bound buffer with the given data
  13470. * @param data defines the data to update
  13471. */
  13472. Engine.prototype.updateArrayBuffer = function (data) {
  13473. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13474. };
  13475. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13476. var pointer = this._currentBufferPointers[indx];
  13477. var changed = false;
  13478. if (!pointer.active) {
  13479. changed = true;
  13480. pointer.active = true;
  13481. pointer.index = indx;
  13482. pointer.size = size;
  13483. pointer.type = type;
  13484. pointer.normalized = normalized;
  13485. pointer.stride = stride;
  13486. pointer.offset = offset;
  13487. pointer.buffer = buffer;
  13488. }
  13489. else {
  13490. if (pointer.buffer !== buffer) {
  13491. pointer.buffer = buffer;
  13492. changed = true;
  13493. }
  13494. if (pointer.size !== size) {
  13495. pointer.size = size;
  13496. changed = true;
  13497. }
  13498. if (pointer.type !== type) {
  13499. pointer.type = type;
  13500. changed = true;
  13501. }
  13502. if (pointer.normalized !== normalized) {
  13503. pointer.normalized = normalized;
  13504. changed = true;
  13505. }
  13506. if (pointer.stride !== stride) {
  13507. pointer.stride = stride;
  13508. changed = true;
  13509. }
  13510. if (pointer.offset !== offset) {
  13511. pointer.offset = offset;
  13512. changed = true;
  13513. }
  13514. }
  13515. if (changed || this._vaoRecordInProgress) {
  13516. this.bindArrayBuffer(buffer);
  13517. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13518. }
  13519. };
  13520. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13521. if (indexBuffer == null) {
  13522. return;
  13523. }
  13524. if (this._cachedIndexBuffer !== indexBuffer) {
  13525. this._cachedIndexBuffer = indexBuffer;
  13526. this.bindIndexBuffer(indexBuffer);
  13527. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13528. }
  13529. };
  13530. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13531. var attributes = effect.getAttributesNames();
  13532. if (!this._vaoRecordInProgress) {
  13533. this._unbindVertexArrayObject();
  13534. }
  13535. this.unbindAllAttributes();
  13536. for (var index = 0; index < attributes.length; index++) {
  13537. var order = effect.getAttributeLocation(index);
  13538. if (order >= 0) {
  13539. var vertexBuffer = vertexBuffers[attributes[index]];
  13540. if (!vertexBuffer) {
  13541. continue;
  13542. }
  13543. this._gl.enableVertexAttribArray(order);
  13544. if (!this._vaoRecordInProgress) {
  13545. this._vertexAttribArraysEnabled[order] = true;
  13546. }
  13547. var buffer = vertexBuffer.getBuffer();
  13548. if (buffer) {
  13549. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13550. if (vertexBuffer.getIsInstanced()) {
  13551. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13552. if (!this._vaoRecordInProgress) {
  13553. this._currentInstanceLocations.push(order);
  13554. this._currentInstanceBuffers.push(buffer);
  13555. }
  13556. }
  13557. }
  13558. }
  13559. }
  13560. };
  13561. /**
  13562. * Records a vertex array object
  13563. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13564. * @param vertexBuffers defines the list of vertex buffers to store
  13565. * @param indexBuffer defines the index buffer to store
  13566. * @param effect defines the effect to store
  13567. * @returns the new vertex array object
  13568. */
  13569. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13570. var vao = this._gl.createVertexArray();
  13571. this._vaoRecordInProgress = true;
  13572. this._gl.bindVertexArray(vao);
  13573. this._mustWipeVertexAttributes = true;
  13574. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13575. this.bindIndexBuffer(indexBuffer);
  13576. this._vaoRecordInProgress = false;
  13577. this._gl.bindVertexArray(null);
  13578. return vao;
  13579. };
  13580. /**
  13581. * Bind a specific vertex array object
  13582. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13583. * @param vertexArrayObject defines the vertex array object to bind
  13584. * @param indexBuffer defines the index buffer to bind
  13585. */
  13586. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13587. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13588. this._cachedVertexArrayObject = vertexArrayObject;
  13589. this._gl.bindVertexArray(vertexArrayObject);
  13590. this._cachedVertexBuffers = null;
  13591. this._cachedIndexBuffer = null;
  13592. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13593. this._mustWipeVertexAttributes = true;
  13594. }
  13595. };
  13596. /**
  13597. * Bind webGl buffers directly to the webGL context
  13598. * @param vertexBuffer defines the vertex buffer to bind
  13599. * @param indexBuffer defines the index buffer to bind
  13600. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13601. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13602. * @param effect defines the effect associated with the vertex buffer
  13603. */
  13604. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13605. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13606. this._cachedVertexBuffers = vertexBuffer;
  13607. this._cachedEffectForVertexBuffers = effect;
  13608. var attributesCount = effect.getAttributesCount();
  13609. this._unbindVertexArrayObject();
  13610. this.unbindAllAttributes();
  13611. var offset = 0;
  13612. for (var index = 0; index < attributesCount; index++) {
  13613. if (index < vertexDeclaration.length) {
  13614. var order = effect.getAttributeLocation(index);
  13615. if (order >= 0) {
  13616. this._gl.enableVertexAttribArray(order);
  13617. this._vertexAttribArraysEnabled[order] = true;
  13618. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13619. }
  13620. offset += vertexDeclaration[index] * 4;
  13621. }
  13622. }
  13623. }
  13624. this._bindIndexBufferWithCache(indexBuffer);
  13625. };
  13626. Engine.prototype._unbindVertexArrayObject = function () {
  13627. if (!this._cachedVertexArrayObject) {
  13628. return;
  13629. }
  13630. this._cachedVertexArrayObject = null;
  13631. this._gl.bindVertexArray(null);
  13632. };
  13633. /**
  13634. * Bind a list of vertex buffers to the webGL context
  13635. * @param vertexBuffers defines the list of vertex buffers to bind
  13636. * @param indexBuffer defines the index buffer to bind
  13637. * @param effect defines the effect associated with the vertex buffers
  13638. */
  13639. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13640. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13641. this._cachedVertexBuffers = vertexBuffers;
  13642. this._cachedEffectForVertexBuffers = effect;
  13643. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13644. }
  13645. this._bindIndexBufferWithCache(indexBuffer);
  13646. };
  13647. /**
  13648. * Unbind all instance attributes
  13649. */
  13650. Engine.prototype.unbindInstanceAttributes = function () {
  13651. var boundBuffer;
  13652. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13653. var instancesBuffer = this._currentInstanceBuffers[i];
  13654. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13655. boundBuffer = instancesBuffer;
  13656. this.bindArrayBuffer(instancesBuffer);
  13657. }
  13658. var offsetLocation = this._currentInstanceLocations[i];
  13659. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13660. }
  13661. this._currentInstanceBuffers.length = 0;
  13662. this._currentInstanceLocations.length = 0;
  13663. };
  13664. /**
  13665. * Release and free the memory of a vertex array object
  13666. * @param vao defines the vertex array object to delete
  13667. */
  13668. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13669. this._gl.deleteVertexArray(vao);
  13670. };
  13671. /** @hidden */
  13672. Engine.prototype._releaseBuffer = function (buffer) {
  13673. buffer.references--;
  13674. if (buffer.references === 0) {
  13675. this._gl.deleteBuffer(buffer);
  13676. return true;
  13677. }
  13678. return false;
  13679. };
  13680. /**
  13681. * Creates a webGL buffer to use with instanciation
  13682. * @param capacity defines the size of the buffer
  13683. * @returns the webGL buffer
  13684. */
  13685. Engine.prototype.createInstancesBuffer = function (capacity) {
  13686. var buffer = this._gl.createBuffer();
  13687. if (!buffer) {
  13688. throw new Error("Unable to create instance buffer");
  13689. }
  13690. buffer.capacity = capacity;
  13691. this.bindArrayBuffer(buffer);
  13692. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13693. return buffer;
  13694. };
  13695. /**
  13696. * Delete a webGL buffer used with instanciation
  13697. * @param buffer defines the webGL buffer to delete
  13698. */
  13699. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13700. this._gl.deleteBuffer(buffer);
  13701. };
  13702. /**
  13703. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13704. * @param instancesBuffer defines the webGL buffer to update and bind
  13705. * @param data defines the data to store in the buffer
  13706. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13707. */
  13708. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13709. this.bindArrayBuffer(instancesBuffer);
  13710. if (data) {
  13711. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13712. }
  13713. if (offsetLocations[0].index !== undefined) {
  13714. var stride = 0;
  13715. for (var i = 0; i < offsetLocations.length; i++) {
  13716. var ai = offsetLocations[i];
  13717. stride += ai.attributeSize * 4;
  13718. }
  13719. for (var i = 0; i < offsetLocations.length; i++) {
  13720. var ai = offsetLocations[i];
  13721. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13722. this._gl.enableVertexAttribArray(ai.index);
  13723. this._vertexAttribArraysEnabled[ai.index] = true;
  13724. }
  13725. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13726. this._gl.vertexAttribDivisor(ai.index, 1);
  13727. this._currentInstanceLocations.push(ai.index);
  13728. this._currentInstanceBuffers.push(instancesBuffer);
  13729. }
  13730. }
  13731. else {
  13732. for (var index = 0; index < 4; index++) {
  13733. var offsetLocation = offsetLocations[index];
  13734. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13735. this._gl.enableVertexAttribArray(offsetLocation);
  13736. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13737. }
  13738. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13739. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13740. this._currentInstanceLocations.push(offsetLocation);
  13741. this._currentInstanceBuffers.push(instancesBuffer);
  13742. }
  13743. }
  13744. };
  13745. /**
  13746. * Apply all cached states (depth, culling, stencil and alpha)
  13747. */
  13748. Engine.prototype.applyStates = function () {
  13749. this._depthCullingState.apply(this._gl);
  13750. this._stencilState.apply(this._gl);
  13751. this._alphaState.apply(this._gl);
  13752. };
  13753. /**
  13754. * Send a draw order
  13755. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13756. * @param indexStart defines the starting index
  13757. * @param indexCount defines the number of index to draw
  13758. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13759. */
  13760. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13761. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13762. };
  13763. /**
  13764. * Draw a list of points
  13765. * @param verticesStart defines the index of first vertex to draw
  13766. * @param verticesCount defines the count of vertices to draw
  13767. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13768. */
  13769. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13770. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13771. };
  13772. /**
  13773. * Draw a list of unindexed primitives
  13774. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13775. * @param verticesStart defines the index of first vertex to draw
  13776. * @param verticesCount defines the count of vertices to draw
  13777. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13778. */
  13779. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13780. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13781. };
  13782. /**
  13783. * Draw a list of indexed primitives
  13784. * @param fillMode defines the primitive to use
  13785. * @param indexStart defines the starting index
  13786. * @param indexCount defines the number of index to draw
  13787. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13788. */
  13789. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13790. // Apply states
  13791. this.applyStates();
  13792. this._drawCalls.addCount(1, false);
  13793. // Render
  13794. var drawMode = this._drawMode(fillMode);
  13795. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13796. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13797. if (instancesCount) {
  13798. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13799. }
  13800. else {
  13801. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13802. }
  13803. };
  13804. /**
  13805. * Draw a list of unindexed primitives
  13806. * @param fillMode defines the primitive to use
  13807. * @param verticesStart defines the index of first vertex to draw
  13808. * @param verticesCount defines the count of vertices to draw
  13809. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13810. */
  13811. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13812. // Apply states
  13813. this.applyStates();
  13814. this._drawCalls.addCount(1, false);
  13815. var drawMode = this._drawMode(fillMode);
  13816. if (instancesCount) {
  13817. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13818. }
  13819. else {
  13820. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13821. }
  13822. };
  13823. Engine.prototype._drawMode = function (fillMode) {
  13824. switch (fillMode) {
  13825. // Triangle views
  13826. case BABYLON.Material.TriangleFillMode:
  13827. return this._gl.TRIANGLES;
  13828. case BABYLON.Material.PointFillMode:
  13829. return this._gl.POINTS;
  13830. case BABYLON.Material.WireFrameFillMode:
  13831. return this._gl.LINES;
  13832. // Draw modes
  13833. case BABYLON.Material.PointListDrawMode:
  13834. return this._gl.POINTS;
  13835. case BABYLON.Material.LineListDrawMode:
  13836. return this._gl.LINES;
  13837. case BABYLON.Material.LineLoopDrawMode:
  13838. return this._gl.LINE_LOOP;
  13839. case BABYLON.Material.LineStripDrawMode:
  13840. return this._gl.LINE_STRIP;
  13841. case BABYLON.Material.TriangleStripDrawMode:
  13842. return this._gl.TRIANGLE_STRIP;
  13843. case BABYLON.Material.TriangleFanDrawMode:
  13844. return this._gl.TRIANGLE_FAN;
  13845. default:
  13846. return this._gl.TRIANGLES;
  13847. }
  13848. };
  13849. // Shaders
  13850. /** @hidden */
  13851. Engine.prototype._releaseEffect = function (effect) {
  13852. if (this._compiledEffects[effect._key]) {
  13853. delete this._compiledEffects[effect._key];
  13854. this._deleteProgram(effect.getProgram());
  13855. }
  13856. };
  13857. /** @hidden */
  13858. Engine.prototype._deleteProgram = function (program) {
  13859. if (program) {
  13860. program.__SPECTOR_rebuildProgram = null;
  13861. if (program.transformFeedback) {
  13862. this.deleteTransformFeedback(program.transformFeedback);
  13863. program.transformFeedback = null;
  13864. }
  13865. this._gl.deleteProgram(program);
  13866. }
  13867. };
  13868. /**
  13869. * Create a new effect (used to store vertex/fragment shaders)
  13870. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13871. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13872. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13873. * @param samplers defines an array of string used to represent textures
  13874. * @param defines defines the string containing the defines to use to compile the shaders
  13875. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13876. * @param onCompiled defines a function to call when the effect creation is successful
  13877. * @param onError defines a function to call when the effect creation has failed
  13878. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13879. * @returns the new Effect
  13880. */
  13881. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13882. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13883. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13884. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13885. if (this._compiledEffects[name]) {
  13886. var compiledEffect = this._compiledEffects[name];
  13887. if (onCompiled && compiledEffect.isReady()) {
  13888. onCompiled(compiledEffect);
  13889. }
  13890. return compiledEffect;
  13891. }
  13892. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13893. effect._key = name;
  13894. this._compiledEffects[name] = effect;
  13895. return effect;
  13896. };
  13897. /**
  13898. * Create an effect to use with particle systems
  13899. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13900. * @param uniformsNames defines a list of attribute names
  13901. * @param samplers defines an array of string used to represent textures
  13902. * @param defines defines the string containing the defines to use to compile the shaders
  13903. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13904. * @param onCompiled defines a function to call when the effect creation is successful
  13905. * @param onError defines a function to call when the effect creation has failed
  13906. * @returns the new Effect
  13907. */
  13908. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13909. if (uniformsNames === void 0) { uniformsNames = []; }
  13910. if (samplers === void 0) { samplers = []; }
  13911. if (defines === void 0) { defines = ""; }
  13912. return this.createEffect({
  13913. vertex: "particles",
  13914. fragmentElement: fragmentName
  13915. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13916. };
  13917. /**
  13918. * Directly creates a webGL program
  13919. * @param vertexCode defines the vertex shader code to use
  13920. * @param fragmentCode defines the fragment shader code to use
  13921. * @param context defines the webGL context to use (if not set, the current one will be used)
  13922. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13923. * @returns the new webGL program
  13924. */
  13925. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13926. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13927. context = context || this._gl;
  13928. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13929. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13930. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13931. };
  13932. /**
  13933. * Creates a webGL program
  13934. * @param vertexCode defines the vertex shader code to use
  13935. * @param fragmentCode defines the fragment shader code to use
  13936. * @param defines defines the string containing the defines to use to compile the shaders
  13937. * @param context defines the webGL context to use (if not set, the current one will be used)
  13938. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13939. * @returns the new webGL program
  13940. */
  13941. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13942. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13943. context = context || this._gl;
  13944. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13945. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13946. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13947. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13948. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13949. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13950. return program;
  13951. };
  13952. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13953. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13954. var shaderProgram = context.createProgram();
  13955. if (!shaderProgram) {
  13956. throw new Error("Unable to create program");
  13957. }
  13958. context.attachShader(shaderProgram, vertexShader);
  13959. context.attachShader(shaderProgram, fragmentShader);
  13960. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13961. var transformFeedback = this.createTransformFeedback();
  13962. this.bindTransformFeedback(transformFeedback);
  13963. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13964. shaderProgram.transformFeedback = transformFeedback;
  13965. }
  13966. context.linkProgram(shaderProgram);
  13967. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13968. this.bindTransformFeedback(null);
  13969. }
  13970. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13971. if (!linked) {
  13972. context.validateProgram(shaderProgram);
  13973. var error = context.getProgramInfoLog(shaderProgram);
  13974. if (error) {
  13975. throw new Error(error);
  13976. }
  13977. }
  13978. context.deleteShader(vertexShader);
  13979. context.deleteShader(fragmentShader);
  13980. return shaderProgram;
  13981. };
  13982. /**
  13983. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13984. * @param shaderProgram defines the webGL program to use
  13985. * @param uniformsNames defines the list of uniform names
  13986. * @returns an array of webGL uniform locations
  13987. */
  13988. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13989. var results = new Array();
  13990. for (var index = 0; index < uniformsNames.length; index++) {
  13991. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13992. }
  13993. return results;
  13994. };
  13995. /**
  13996. * Gets the lsit of active attributes for a given webGL program
  13997. * @param shaderProgram defines the webGL program to use
  13998. * @param attributesNames defines the list of attribute names to get
  13999. * @returns an array of indices indicating the offset of each attribute
  14000. */
  14001. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14002. var results = [];
  14003. for (var index = 0; index < attributesNames.length; index++) {
  14004. try {
  14005. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14006. }
  14007. catch (e) {
  14008. results.push(-1);
  14009. }
  14010. }
  14011. return results;
  14012. };
  14013. /**
  14014. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14015. * @param effect defines the effect to activate
  14016. */
  14017. Engine.prototype.enableEffect = function (effect) {
  14018. if (!effect) {
  14019. return;
  14020. }
  14021. // Use program
  14022. this.bindSamplers(effect);
  14023. this._currentEffect = effect;
  14024. if (effect.onBind) {
  14025. effect.onBind(effect);
  14026. }
  14027. effect.onBindObservable.notifyObservers(effect);
  14028. };
  14029. /**
  14030. * Set the value of an uniform to an array of int32
  14031. * @param uniform defines the webGL uniform location where to store the value
  14032. * @param array defines the array of int32 to store
  14033. */
  14034. Engine.prototype.setIntArray = function (uniform, array) {
  14035. if (!uniform)
  14036. return;
  14037. this._gl.uniform1iv(uniform, array);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to an array of int32 (stored as vec2)
  14041. * @param uniform defines the webGL uniform location where to store the value
  14042. * @param array defines the array of int32 to store
  14043. */
  14044. Engine.prototype.setIntArray2 = function (uniform, array) {
  14045. if (!uniform || array.length % 2 !== 0)
  14046. return;
  14047. this._gl.uniform2iv(uniform, array);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to an array of int32 (stored as vec3)
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param array defines the array of int32 to store
  14053. */
  14054. Engine.prototype.setIntArray3 = function (uniform, array) {
  14055. if (!uniform || array.length % 3 !== 0)
  14056. return;
  14057. this._gl.uniform3iv(uniform, array);
  14058. };
  14059. /**
  14060. * Set the value of an uniform to an array of int32 (stored as vec4)
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param array defines the array of int32 to store
  14063. */
  14064. Engine.prototype.setIntArray4 = function (uniform, array) {
  14065. if (!uniform || array.length % 4 !== 0)
  14066. return;
  14067. this._gl.uniform4iv(uniform, array);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to an array of float32
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param array defines the array of float32 to store
  14073. */
  14074. Engine.prototype.setFloatArray = function (uniform, array) {
  14075. if (!uniform)
  14076. return;
  14077. this._gl.uniform1fv(uniform, array);
  14078. };
  14079. /**
  14080. * Set the value of an uniform to an array of float32 (stored as vec2)
  14081. * @param uniform defines the webGL uniform location where to store the value
  14082. * @param array defines the array of float32 to store
  14083. */
  14084. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14085. if (!uniform || array.length % 2 !== 0)
  14086. return;
  14087. this._gl.uniform2fv(uniform, array);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to an array of float32 (stored as vec3)
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param array defines the array of float32 to store
  14093. */
  14094. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14095. if (!uniform || array.length % 3 !== 0)
  14096. return;
  14097. this._gl.uniform3fv(uniform, array);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to an array of float32 (stored as vec4)
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param array defines the array of float32 to store
  14103. */
  14104. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14105. if (!uniform || array.length % 4 !== 0)
  14106. return;
  14107. this._gl.uniform4fv(uniform, array);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to an array of number
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param array defines the array of number to store
  14113. */
  14114. Engine.prototype.setArray = function (uniform, array) {
  14115. if (!uniform)
  14116. return;
  14117. this._gl.uniform1fv(uniform, array);
  14118. };
  14119. /**
  14120. * Set the value of an uniform to an array of number (stored as vec2)
  14121. * @param uniform defines the webGL uniform location where to store the value
  14122. * @param array defines the array of number to store
  14123. */
  14124. Engine.prototype.setArray2 = function (uniform, array) {
  14125. if (!uniform || array.length % 2 !== 0)
  14126. return;
  14127. this._gl.uniform2fv(uniform, array);
  14128. };
  14129. /**
  14130. * Set the value of an uniform to an array of number (stored as vec3)
  14131. * @param uniform defines the webGL uniform location where to store the value
  14132. * @param array defines the array of number to store
  14133. */
  14134. Engine.prototype.setArray3 = function (uniform, array) {
  14135. if (!uniform || array.length % 3 !== 0)
  14136. return;
  14137. this._gl.uniform3fv(uniform, array);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to an array of number (stored as vec4)
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param array defines the array of number to store
  14143. */
  14144. Engine.prototype.setArray4 = function (uniform, array) {
  14145. if (!uniform || array.length % 4 !== 0)
  14146. return;
  14147. this._gl.uniform4fv(uniform, array);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to an array of float32 (stored as matrices)
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param matrices defines the array of float32 to store
  14153. */
  14154. Engine.prototype.setMatrices = function (uniform, matrices) {
  14155. if (!uniform)
  14156. return;
  14157. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14158. };
  14159. /**
  14160. * Set the value of an uniform to a matrix
  14161. * @param uniform defines the webGL uniform location where to store the value
  14162. * @param matrix defines the matrix to store
  14163. */
  14164. Engine.prototype.setMatrix = function (uniform, matrix) {
  14165. if (!uniform)
  14166. return;
  14167. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14168. };
  14169. /**
  14170. * Set the value of an uniform to a matrix (3x3)
  14171. * @param uniform defines the webGL uniform location where to store the value
  14172. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14173. */
  14174. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14175. if (!uniform)
  14176. return;
  14177. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14178. };
  14179. /**
  14180. * Set the value of an uniform to a matrix (2x2)
  14181. * @param uniform defines the webGL uniform location where to store the value
  14182. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14183. */
  14184. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14185. if (!uniform)
  14186. return;
  14187. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14188. };
  14189. /**
  14190. * Set the value of an uniform to a number (int)
  14191. * @param uniform defines the webGL uniform location where to store the value
  14192. * @param value defines the int number to store
  14193. */
  14194. Engine.prototype.setInt = function (uniform, value) {
  14195. if (!uniform)
  14196. return;
  14197. this._gl.uniform1i(uniform, value);
  14198. };
  14199. /**
  14200. * Set the value of an uniform to a number (float)
  14201. * @param uniform defines the webGL uniform location where to store the value
  14202. * @param value defines the float number to store
  14203. */
  14204. Engine.prototype.setFloat = function (uniform, value) {
  14205. if (!uniform)
  14206. return;
  14207. this._gl.uniform1f(uniform, value);
  14208. };
  14209. /**
  14210. * Set the value of an uniform to a vec2
  14211. * @param uniform defines the webGL uniform location where to store the value
  14212. * @param x defines the 1st component of the value
  14213. * @param y defines the 2nd component of the value
  14214. */
  14215. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14216. if (!uniform)
  14217. return;
  14218. this._gl.uniform2f(uniform, x, y);
  14219. };
  14220. /**
  14221. * Set the value of an uniform to a vec3
  14222. * @param uniform defines the webGL uniform location where to store the value
  14223. * @param x defines the 1st component of the value
  14224. * @param y defines the 2nd component of the value
  14225. * @param z defines the 3rd component of the value
  14226. */
  14227. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14228. if (!uniform)
  14229. return;
  14230. this._gl.uniform3f(uniform, x, y, z);
  14231. };
  14232. /**
  14233. * Set the value of an uniform to a boolean
  14234. * @param uniform defines the webGL uniform location where to store the value
  14235. * @param bool defines the boolean to store
  14236. */
  14237. Engine.prototype.setBool = function (uniform, bool) {
  14238. if (!uniform)
  14239. return;
  14240. this._gl.uniform1i(uniform, bool);
  14241. };
  14242. /**
  14243. * Set the value of an uniform to a vec4
  14244. * @param uniform defines the webGL uniform location where to store the value
  14245. * @param x defines the 1st component of the value
  14246. * @param y defines the 2nd component of the value
  14247. * @param z defines the 3rd component of the value
  14248. * @param w defines the 4th component of the value
  14249. */
  14250. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14251. if (!uniform)
  14252. return;
  14253. this._gl.uniform4f(uniform, x, y, z, w);
  14254. };
  14255. /**
  14256. * Set the value of an uniform to a Color3
  14257. * @param uniform defines the webGL uniform location where to store the value
  14258. * @param color3 defines the color to store
  14259. */
  14260. Engine.prototype.setColor3 = function (uniform, color3) {
  14261. if (!uniform)
  14262. return;
  14263. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14264. };
  14265. /**
  14266. * Set the value of an uniform to a Color3 and an alpha value
  14267. * @param uniform defines the webGL uniform location where to store the value
  14268. * @param color3 defines the color to store
  14269. * @param alpha defines the alpha component to store
  14270. */
  14271. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14272. if (!uniform)
  14273. return;
  14274. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14275. };
  14276. /**
  14277. * Sets a Color4 on a uniform variable
  14278. * @param uniform defines the uniform location
  14279. * @param color4 defines the value to be set
  14280. */
  14281. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14282. if (!uniform)
  14283. return;
  14284. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14285. };
  14286. // States
  14287. /**
  14288. * Set various states to the webGL context
  14289. * @param culling defines backface culling state
  14290. * @param zOffset defines the value to apply to zOffset (0 by default)
  14291. * @param force defines if states must be applied even if cache is up to date
  14292. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14293. */
  14294. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14295. if (zOffset === void 0) { zOffset = 0; }
  14296. if (reverseSide === void 0) { reverseSide = false; }
  14297. // Culling
  14298. if (this._depthCullingState.cull !== culling || force) {
  14299. this._depthCullingState.cull = culling;
  14300. }
  14301. // Cull face
  14302. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14303. if (this._depthCullingState.cullFace !== cullFace || force) {
  14304. this._depthCullingState.cullFace = cullFace;
  14305. }
  14306. // Z offset
  14307. this.setZOffset(zOffset);
  14308. // Front face
  14309. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14310. if (this._depthCullingState.frontFace !== frontFace || force) {
  14311. this._depthCullingState.frontFace = frontFace;
  14312. }
  14313. };
  14314. /**
  14315. * Set the z offset to apply to current rendering
  14316. * @param value defines the offset to apply
  14317. */
  14318. Engine.prototype.setZOffset = function (value) {
  14319. this._depthCullingState.zOffset = value;
  14320. };
  14321. /**
  14322. * Gets the current value of the zOffset
  14323. * @returns the current zOffset state
  14324. */
  14325. Engine.prototype.getZOffset = function () {
  14326. return this._depthCullingState.zOffset;
  14327. };
  14328. /**
  14329. * Enable or disable depth buffering
  14330. * @param enable defines the state to set
  14331. */
  14332. Engine.prototype.setDepthBuffer = function (enable) {
  14333. this._depthCullingState.depthTest = enable;
  14334. };
  14335. /**
  14336. * Gets a boolean indicating if depth writing is enabled
  14337. * @returns the current depth writing state
  14338. */
  14339. Engine.prototype.getDepthWrite = function () {
  14340. return this._depthCullingState.depthMask;
  14341. };
  14342. /**
  14343. * Enable or disable depth writing
  14344. * @param enable defines the state to set
  14345. */
  14346. Engine.prototype.setDepthWrite = function (enable) {
  14347. this._depthCullingState.depthMask = enable;
  14348. };
  14349. /**
  14350. * Enable or disable color writing
  14351. * @param enable defines the state to set
  14352. */
  14353. Engine.prototype.setColorWrite = function (enable) {
  14354. this._gl.colorMask(enable, enable, enable, enable);
  14355. this._colorWrite = enable;
  14356. };
  14357. /**
  14358. * Gets a boolean indicating if color writing is enabled
  14359. * @returns the current color writing state
  14360. */
  14361. Engine.prototype.getColorWrite = function () {
  14362. return this._colorWrite;
  14363. };
  14364. /**
  14365. * Sets alpha constants used by some alpha blending modes
  14366. * @param r defines the red component
  14367. * @param g defines the green component
  14368. * @param b defines the blue component
  14369. * @param a defines the alpha component
  14370. */
  14371. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14372. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14373. };
  14374. /**
  14375. * Sets the current alpha mode
  14376. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14377. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14378. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14379. */
  14380. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14381. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14382. if (this._alphaMode === mode) {
  14383. return;
  14384. }
  14385. switch (mode) {
  14386. case Engine.ALPHA_DISABLE:
  14387. this._alphaState.alphaBlend = false;
  14388. break;
  14389. case Engine.ALPHA_PREMULTIPLIED:
  14390. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14391. this._alphaState.alphaBlend = true;
  14392. break;
  14393. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14395. this._alphaState.alphaBlend = true;
  14396. break;
  14397. case Engine.ALPHA_COMBINE:
  14398. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14399. this._alphaState.alphaBlend = true;
  14400. break;
  14401. case Engine.ALPHA_ONEONE:
  14402. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14403. this._alphaState.alphaBlend = true;
  14404. break;
  14405. case Engine.ALPHA_ADD:
  14406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14407. this._alphaState.alphaBlend = true;
  14408. break;
  14409. case Engine.ALPHA_SUBTRACT:
  14410. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14411. this._alphaState.alphaBlend = true;
  14412. break;
  14413. case Engine.ALPHA_MULTIPLY:
  14414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14415. this._alphaState.alphaBlend = true;
  14416. break;
  14417. case Engine.ALPHA_MAXIMIZED:
  14418. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14419. this._alphaState.alphaBlend = true;
  14420. break;
  14421. case Engine.ALPHA_INTERPOLATE:
  14422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14423. this._alphaState.alphaBlend = true;
  14424. break;
  14425. case Engine.ALPHA_SCREENMODE:
  14426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14427. this._alphaState.alphaBlend = true;
  14428. break;
  14429. }
  14430. if (!noDepthWriteChange) {
  14431. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14432. }
  14433. this._alphaMode = mode;
  14434. };
  14435. /**
  14436. * Gets the current alpha mode
  14437. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14438. * @returns the current alpha mode
  14439. */
  14440. Engine.prototype.getAlphaMode = function () {
  14441. return this._alphaMode;
  14442. };
  14443. // Textures
  14444. /**
  14445. * Force the entire cache to be cleared
  14446. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14447. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14448. */
  14449. Engine.prototype.wipeCaches = function (bruteForce) {
  14450. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14451. return;
  14452. }
  14453. this._currentEffect = null;
  14454. if (bruteForce) {
  14455. this.resetTextureCache();
  14456. this._currentProgram = null;
  14457. this._stencilState.reset();
  14458. this._depthCullingState.reset();
  14459. this.setDepthFunctionToLessOrEqual();
  14460. this._alphaState.reset();
  14461. }
  14462. this._resetVertexBufferBinding();
  14463. this._cachedIndexBuffer = null;
  14464. this._cachedEffectForVertexBuffers = null;
  14465. this._unbindVertexArrayObject();
  14466. this.bindIndexBuffer(null);
  14467. };
  14468. /**
  14469. * Set the compressed texture format to use, based on the formats you have, and the formats
  14470. * supported by the hardware / browser.
  14471. *
  14472. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14473. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14474. * to API arguments needed to compressed textures. This puts the burden on the container
  14475. * generator to house the arcane code for determining these for current & future formats.
  14476. *
  14477. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14478. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14479. *
  14480. * Note: The result of this call is not taken into account when a texture is base64.
  14481. *
  14482. * @param formatsAvailable defines the list of those format families you have created
  14483. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14484. *
  14485. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14486. * @returns The extension selected.
  14487. */
  14488. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14489. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14490. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14491. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14492. return this._textureFormatInUse = this._texturesSupported[i];
  14493. }
  14494. }
  14495. }
  14496. // actively set format to nothing, to allow this to be called more than once
  14497. // and possibly fail the 2nd time
  14498. this._textureFormatInUse = null;
  14499. return null;
  14500. };
  14501. /** @hidden */
  14502. Engine.prototype._createTexture = function () {
  14503. var texture = this._gl.createTexture();
  14504. if (!texture) {
  14505. throw new Error("Unable to create texture");
  14506. }
  14507. return texture;
  14508. };
  14509. /**
  14510. * Usually called from BABYLON.Texture.ts.
  14511. * Passed information to create a WebGLTexture
  14512. * @param urlArg defines a value which contains one of the following:
  14513. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14514. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14515. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14516. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14517. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14518. * @param scene needed for loading to the correct scene
  14519. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14520. * @param onLoad optional callback to be called upon successful completion
  14521. * @param onError optional callback to be called upon failure
  14522. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14523. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14524. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14525. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14526. */
  14527. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14528. var _this = this;
  14529. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14530. if (onLoad === void 0) { onLoad = null; }
  14531. if (onError === void 0) { onError = null; }
  14532. if (buffer === void 0) { buffer = null; }
  14533. if (fallback === void 0) { fallback = null; }
  14534. if (format === void 0) { format = null; }
  14535. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14536. var fromData = url.substr(0, 5) === "data:";
  14537. var fromBlob = url.substr(0, 5) === "blob:";
  14538. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14539. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14540. // establish the file extension, if possible
  14541. var lastDot = url.lastIndexOf('.');
  14542. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14543. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14544. var isTGA = (extension.indexOf(".tga") === 0);
  14545. // determine if a ktx file should be substituted
  14546. var isKTX = false;
  14547. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14548. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14549. isKTX = true;
  14550. }
  14551. if (scene) {
  14552. scene._addPendingData(texture);
  14553. }
  14554. texture.url = url;
  14555. texture.generateMipMaps = !noMipmap;
  14556. texture.samplingMode = samplingMode;
  14557. texture.invertY = invertY;
  14558. if (!this._doNotHandleContextLost) {
  14559. // Keep a link to the buffer only if we plan to handle context lost
  14560. texture._buffer = buffer;
  14561. }
  14562. var onLoadObserver = null;
  14563. if (onLoad && !fallback) {
  14564. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14565. }
  14566. if (!fallback)
  14567. this._internalTexturesCache.push(texture);
  14568. var onerror = function (message, exception) {
  14569. if (scene) {
  14570. scene._removePendingData(texture);
  14571. }
  14572. if (onLoadObserver) {
  14573. texture.onLoadedObservable.remove(onLoadObserver);
  14574. }
  14575. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14576. if (isKTX) {
  14577. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14578. }
  14579. else if (BABYLON.Tools.UseFallbackTexture) {
  14580. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14581. }
  14582. if (onError) {
  14583. onError(message || "Unknown error", exception);
  14584. }
  14585. };
  14586. var callback = null;
  14587. // processing for non-image formats
  14588. if (isKTX || isTGA || isDDS) {
  14589. if (isKTX) {
  14590. callback = function (data) {
  14591. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14592. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14593. ktx.uploadLevels(_this._gl, !noMipmap);
  14594. return false;
  14595. }, samplingMode);
  14596. };
  14597. }
  14598. else if (isTGA) {
  14599. callback = function (arrayBuffer) {
  14600. var data = new Uint8Array(arrayBuffer);
  14601. var header = BABYLON.TGATools.GetTGAHeader(data);
  14602. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14603. BABYLON.TGATools.UploadContent(_this._gl, data);
  14604. return false;
  14605. }, samplingMode);
  14606. };
  14607. }
  14608. else if (isDDS) {
  14609. callback = function (data) {
  14610. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14611. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14612. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14613. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14614. return false;
  14615. }, samplingMode);
  14616. };
  14617. }
  14618. if (!buffer) {
  14619. this._loadFile(url, function (data) {
  14620. if (callback) {
  14621. callback(data);
  14622. }
  14623. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14624. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14625. });
  14626. }
  14627. else {
  14628. if (callback) {
  14629. callback(buffer);
  14630. }
  14631. }
  14632. // image format processing
  14633. }
  14634. else {
  14635. var onload = function (img) {
  14636. if (fromBlob && !_this._doNotHandleContextLost) {
  14637. // We need to store the image if we need to rebuild the texture
  14638. // in case of a webgl context lost
  14639. texture._buffer = img;
  14640. }
  14641. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14642. var gl = _this._gl;
  14643. var isPot = (img.width === potWidth && img.height === potHeight);
  14644. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14645. if (isPot) {
  14646. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14647. return false;
  14648. }
  14649. // Using shaders to rescale because canvas.drawImage is lossy
  14650. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14651. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14652. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14653. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14656. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14657. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14658. _this._releaseTexture(source);
  14659. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14660. continuationCallback();
  14661. });
  14662. return true;
  14663. }, samplingMode);
  14664. };
  14665. if (!fromData || isBase64) {
  14666. if (buffer instanceof HTMLImageElement) {
  14667. onload(buffer);
  14668. }
  14669. else {
  14670. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14671. }
  14672. }
  14673. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14674. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14675. }
  14676. else {
  14677. onload(buffer);
  14678. }
  14679. }
  14680. return texture;
  14681. };
  14682. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14683. var _this = this;
  14684. var rtt = this.createRenderTargetTexture({
  14685. width: destination.width,
  14686. height: destination.height,
  14687. }, {
  14688. generateMipMaps: false,
  14689. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14690. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14691. generateDepthBuffer: false,
  14692. generateStencilBuffer: false
  14693. });
  14694. if (!this._rescalePostProcess) {
  14695. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14696. }
  14697. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14698. _this._rescalePostProcess.onApply = function (effect) {
  14699. effect._bindTexture("textureSampler", source);
  14700. };
  14701. var hostingScene = scene;
  14702. if (!hostingScene) {
  14703. hostingScene = _this.scenes[_this.scenes.length - 1];
  14704. }
  14705. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14706. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14707. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14708. _this.unBindFramebuffer(rtt);
  14709. _this._releaseTexture(rtt);
  14710. if (onComplete) {
  14711. onComplete();
  14712. }
  14713. });
  14714. };
  14715. /**
  14716. * Update a raw texture
  14717. * @param texture defines the texture to update
  14718. * @param data defines the data to store in the texture
  14719. * @param format defines the format of the data
  14720. * @param invertY defines if data must be stored with Y axis inverted
  14721. * @param compression defines the compression used (null by default)
  14722. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14723. */
  14724. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14725. if (compression === void 0) { compression = null; }
  14726. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14727. if (!texture) {
  14728. return;
  14729. }
  14730. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14731. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14732. // babylon's internalFormat but gl's texImage2D format
  14733. var internalFormat = this._getInternalFormat(format);
  14734. var textureType = this._getWebGLTextureType(type);
  14735. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14736. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14737. if (!this._doNotHandleContextLost) {
  14738. texture._bufferView = data;
  14739. texture.format = format;
  14740. texture.type = type;
  14741. texture.invertY = invertY;
  14742. texture._compression = compression;
  14743. }
  14744. if (texture.width % 4 !== 0) {
  14745. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14746. }
  14747. if (compression && data) {
  14748. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14749. }
  14750. else {
  14751. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14752. }
  14753. if (texture.generateMipMaps) {
  14754. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14755. }
  14756. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14757. // this.resetTextureCache();
  14758. texture.isReady = true;
  14759. };
  14760. /**
  14761. * Creates a raw texture
  14762. * @param data defines the data to store in the texture
  14763. * @param width defines the width of the texture
  14764. * @param height defines the height of the texture
  14765. * @param format defines the format of the data
  14766. * @param generateMipMaps defines if the engine should generate the mip levels
  14767. * @param invertY defines if data must be stored with Y axis inverted
  14768. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14769. * @param compression defines the compression used (null by default)
  14770. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14771. * @returns the raw texture inside an InternalTexture
  14772. */
  14773. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14774. if (compression === void 0) { compression = null; }
  14775. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14776. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14777. texture.baseWidth = width;
  14778. texture.baseHeight = height;
  14779. texture.width = width;
  14780. texture.height = height;
  14781. texture.format = format;
  14782. texture.generateMipMaps = generateMipMaps;
  14783. texture.samplingMode = samplingMode;
  14784. texture.invertY = invertY;
  14785. texture._compression = compression;
  14786. texture.type = type;
  14787. if (!this._doNotHandleContextLost) {
  14788. texture._bufferView = data;
  14789. }
  14790. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14791. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14792. // Filters
  14793. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14794. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14795. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14796. if (generateMipMaps) {
  14797. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14798. }
  14799. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14800. this._internalTexturesCache.push(texture);
  14801. return texture;
  14802. };
  14803. /**
  14804. * Creates a dynamic texture
  14805. * @param width defines the width of the texture
  14806. * @param height defines the height of the texture
  14807. * @param generateMipMaps defines if the engine should generate the mip levels
  14808. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14809. * @returns the dynamic texture inside an InternalTexture
  14810. */
  14811. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14812. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14813. texture.baseWidth = width;
  14814. texture.baseHeight = height;
  14815. if (generateMipMaps) {
  14816. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14817. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14818. }
  14819. // this.resetTextureCache();
  14820. texture.width = width;
  14821. texture.height = height;
  14822. texture.isReady = false;
  14823. texture.generateMipMaps = generateMipMaps;
  14824. texture.samplingMode = samplingMode;
  14825. this.updateTextureSamplingMode(samplingMode, texture);
  14826. this._internalTexturesCache.push(texture);
  14827. return texture;
  14828. };
  14829. /**
  14830. * Update the sampling mode of a given texture
  14831. * @param samplingMode defines the required sampling mode
  14832. * @param texture defines the texture to update
  14833. */
  14834. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14835. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14836. if (texture.isCube) {
  14837. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14838. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14839. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14840. }
  14841. else if (texture.is3D) {
  14842. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14843. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14844. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14845. }
  14846. else {
  14847. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14848. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14849. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14850. }
  14851. texture.samplingMode = samplingMode;
  14852. };
  14853. /**
  14854. * Update the content of a dynamic texture
  14855. * @param texture defines the texture to update
  14856. * @param canvas defines the canvas containing the source
  14857. * @param invertY defines if data must be stored with Y axis inverted
  14858. * @param premulAlpha defines if alpha is stored as premultiplied
  14859. * @param format defines the format of the data
  14860. */
  14861. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14862. if (premulAlpha === void 0) { premulAlpha = false; }
  14863. if (!texture) {
  14864. return;
  14865. }
  14866. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14867. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14868. if (premulAlpha) {
  14869. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14870. }
  14871. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14872. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14873. if (texture.generateMipMaps) {
  14874. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14875. }
  14876. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14877. if (premulAlpha) {
  14878. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14879. }
  14880. texture.isReady = true;
  14881. };
  14882. /**
  14883. * Update a video texture
  14884. * @param texture defines the texture to update
  14885. * @param video defines the video element to use
  14886. * @param invertY defines if data must be stored with Y axis inverted
  14887. */
  14888. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14889. if (!texture || texture._isDisabled) {
  14890. return;
  14891. }
  14892. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14893. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14894. try {
  14895. // Testing video texture support
  14896. if (this._videoTextureSupported === undefined) {
  14897. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14898. if (this._gl.getError() !== 0) {
  14899. this._videoTextureSupported = false;
  14900. }
  14901. else {
  14902. this._videoTextureSupported = true;
  14903. }
  14904. }
  14905. // Copy video through the current working canvas if video texture is not supported
  14906. if (!this._videoTextureSupported) {
  14907. if (!texture._workingCanvas) {
  14908. texture._workingCanvas = document.createElement("canvas");
  14909. var context = texture._workingCanvas.getContext("2d");
  14910. if (!context) {
  14911. throw new Error("Unable to get 2d context");
  14912. }
  14913. texture._workingContext = context;
  14914. texture._workingCanvas.width = texture.width;
  14915. texture._workingCanvas.height = texture.height;
  14916. }
  14917. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14918. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14919. }
  14920. else {
  14921. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14922. }
  14923. if (texture.generateMipMaps) {
  14924. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14925. }
  14926. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14927. // this.resetTextureCache();
  14928. texture.isReady = true;
  14929. }
  14930. catch (ex) {
  14931. // Something unexpected
  14932. // Let's disable the texture
  14933. texture._isDisabled = true;
  14934. }
  14935. };
  14936. /**
  14937. * Updates a depth texture Comparison Mode and Function.
  14938. * If the comparison Function is equal to 0, the mode will be set to none.
  14939. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14940. * @param texture The texture to set the comparison function for
  14941. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14942. */
  14943. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14944. if (this.webGLVersion === 1) {
  14945. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14946. return;
  14947. }
  14948. var gl = this._gl;
  14949. if (texture.isCube) {
  14950. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14951. if (comparisonFunction === 0) {
  14952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14954. }
  14955. else {
  14956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14957. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14958. }
  14959. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14960. }
  14961. else {
  14962. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14963. if (comparisonFunction === 0) {
  14964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14965. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14966. }
  14967. else {
  14968. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14969. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14970. }
  14971. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14972. }
  14973. texture._comparisonFunction = comparisonFunction;
  14974. };
  14975. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14976. var width = size.width || size;
  14977. var height = size.height || size;
  14978. internalTexture.baseWidth = width;
  14979. internalTexture.baseHeight = height;
  14980. internalTexture.width = width;
  14981. internalTexture.height = height;
  14982. internalTexture.isReady = true;
  14983. internalTexture.samples = 1;
  14984. internalTexture.generateMipMaps = false;
  14985. internalTexture._generateDepthBuffer = true;
  14986. internalTexture._generateStencilBuffer = generateStencil;
  14987. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14988. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14989. internalTexture._comparisonFunction = comparisonFunction;
  14990. var gl = this._gl;
  14991. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14992. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14993. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14994. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14995. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14996. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14997. if (comparisonFunction === 0) {
  14998. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14999. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15000. }
  15001. else {
  15002. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15003. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15004. }
  15005. };
  15006. /**
  15007. * Creates a depth stencil texture.
  15008. * This is only available in WebGL 2 or with the depth texture extension available.
  15009. * @param size The size of face edge in the texture.
  15010. * @param options The options defining the texture.
  15011. * @returns The texture
  15012. */
  15013. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15014. if (options.isCube) {
  15015. var width = size.width || size;
  15016. return this._createDepthStencilCubeTexture(width, options);
  15017. }
  15018. else {
  15019. return this._createDepthStencilTexture(size, options);
  15020. }
  15021. };
  15022. /**
  15023. * Creates a depth stencil texture.
  15024. * This is only available in WebGL 2 or with the depth texture extension available.
  15025. * @param size The size of face edge in the texture.
  15026. * @param options The options defining the texture.
  15027. * @returns The texture
  15028. */
  15029. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15030. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15031. if (!this._caps.depthTextureExtension) {
  15032. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15033. return internalTexture;
  15034. }
  15035. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15036. var gl = this._gl;
  15037. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15038. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15039. if (this.webGLVersion > 1) {
  15040. if (internalOptions.generateStencil) {
  15041. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15042. }
  15043. else {
  15044. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15045. }
  15046. }
  15047. else {
  15048. if (internalOptions.generateStencil) {
  15049. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15050. }
  15051. else {
  15052. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15053. }
  15054. }
  15055. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15056. return internalTexture;
  15057. };
  15058. /**
  15059. * Creates a depth stencil cube texture.
  15060. * This is only available in WebGL 2.
  15061. * @param size The size of face edge in the cube texture.
  15062. * @param options The options defining the cube texture.
  15063. * @returns The cube texture
  15064. */
  15065. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15066. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15067. internalTexture.isCube = true;
  15068. if (this.webGLVersion === 1) {
  15069. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15070. return internalTexture;
  15071. }
  15072. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15073. var gl = this._gl;
  15074. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15075. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15076. // Create the depth/stencil buffer
  15077. for (var face = 0; face < 6; face++) {
  15078. if (internalOptions.generateStencil) {
  15079. 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);
  15080. }
  15081. else {
  15082. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15083. }
  15084. }
  15085. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15086. return internalTexture;
  15087. };
  15088. /**
  15089. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15090. * @param renderTarget The render target to set the frame buffer for
  15091. */
  15092. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15093. // Create the framebuffer
  15094. var internalTexture = renderTarget.getInternalTexture();
  15095. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15096. return;
  15097. }
  15098. var gl = this._gl;
  15099. var depthStencilTexture = renderTarget.depthStencilTexture;
  15100. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15101. if (depthStencilTexture.isCube) {
  15102. if (depthStencilTexture._generateStencilBuffer) {
  15103. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15104. }
  15105. else {
  15106. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15107. }
  15108. }
  15109. else {
  15110. if (depthStencilTexture._generateStencilBuffer) {
  15111. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15112. }
  15113. else {
  15114. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15115. }
  15116. }
  15117. this.bindUnboundFramebuffer(null);
  15118. };
  15119. /**
  15120. * Creates a new render target texture
  15121. * @param size defines the size of the texture
  15122. * @param options defines the options used to create the texture
  15123. * @returns a new render target texture stored in an InternalTexture
  15124. */
  15125. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15126. var fullOptions = new RenderTargetCreationOptions();
  15127. if (options !== undefined && typeof options === "object") {
  15128. fullOptions.generateMipMaps = options.generateMipMaps;
  15129. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15130. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15131. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15132. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15133. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15134. }
  15135. else {
  15136. fullOptions.generateMipMaps = options;
  15137. fullOptions.generateDepthBuffer = true;
  15138. fullOptions.generateStencilBuffer = false;
  15139. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15140. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15141. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15142. }
  15143. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15144. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15145. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15146. }
  15147. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15148. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15149. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15150. }
  15151. var gl = this._gl;
  15152. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15153. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15154. var width = size.width || size;
  15155. var height = size.height || size;
  15156. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15157. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15158. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15159. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15160. }
  15161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15165. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15166. // Create the framebuffer
  15167. var currentFrameBuffer = this._currentFramebuffer;
  15168. var framebuffer = gl.createFramebuffer();
  15169. this.bindUnboundFramebuffer(framebuffer);
  15170. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15171. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15172. if (fullOptions.generateMipMaps) {
  15173. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15174. }
  15175. // Unbind
  15176. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15177. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15178. this.bindUnboundFramebuffer(currentFrameBuffer);
  15179. texture._framebuffer = framebuffer;
  15180. texture.baseWidth = width;
  15181. texture.baseHeight = height;
  15182. texture.width = width;
  15183. texture.height = height;
  15184. texture.isReady = true;
  15185. texture.samples = 1;
  15186. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15187. texture.samplingMode = fullOptions.samplingMode;
  15188. texture.type = fullOptions.type;
  15189. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15190. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15191. // this.resetTextureCache();
  15192. this._internalTexturesCache.push(texture);
  15193. return texture;
  15194. };
  15195. /**
  15196. * Create a multi render target texture
  15197. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15198. * @param size defines the size of the texture
  15199. * @param options defines the creation options
  15200. * @returns the cube texture as an InternalTexture
  15201. */
  15202. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15203. var generateMipMaps = false;
  15204. var generateDepthBuffer = true;
  15205. var generateStencilBuffer = false;
  15206. var generateDepthTexture = false;
  15207. var textureCount = 1;
  15208. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15209. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15210. var types = new Array();
  15211. var samplingModes = new Array();
  15212. if (options !== undefined) {
  15213. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15214. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15215. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15216. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15217. textureCount = options.textureCount || 1;
  15218. if (options.types) {
  15219. types = options.types;
  15220. }
  15221. if (options.samplingModes) {
  15222. samplingModes = options.samplingModes;
  15223. }
  15224. }
  15225. var gl = this._gl;
  15226. // Create the framebuffer
  15227. var framebuffer = gl.createFramebuffer();
  15228. this.bindUnboundFramebuffer(framebuffer);
  15229. var width = size.width || size;
  15230. var height = size.height || size;
  15231. var textures = [];
  15232. var attachments = [];
  15233. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15234. for (var i = 0; i < textureCount; i++) {
  15235. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15236. var type = types[i] || defaultType;
  15237. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15238. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15239. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15240. }
  15241. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15242. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15243. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15244. }
  15245. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15246. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15247. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15248. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15249. }
  15250. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15251. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15252. textures.push(texture);
  15253. attachments.push(attachment);
  15254. gl.activeTexture(gl["TEXTURE" + i]);
  15255. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15259. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15260. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15261. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15262. if (generateMipMaps) {
  15263. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15264. }
  15265. // Unbind
  15266. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15267. texture._framebuffer = framebuffer;
  15268. texture._depthStencilBuffer = depthStencilBuffer;
  15269. texture.baseWidth = width;
  15270. texture.baseHeight = height;
  15271. texture.width = width;
  15272. texture.height = height;
  15273. texture.isReady = true;
  15274. texture.samples = 1;
  15275. texture.generateMipMaps = generateMipMaps;
  15276. texture.samplingMode = samplingMode;
  15277. texture.type = type;
  15278. texture._generateDepthBuffer = generateDepthBuffer;
  15279. texture._generateStencilBuffer = generateStencilBuffer;
  15280. texture._attachments = attachments;
  15281. this._internalTexturesCache.push(texture);
  15282. }
  15283. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15284. // Depth texture
  15285. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15286. gl.activeTexture(gl.TEXTURE0);
  15287. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15288. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15289. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15291. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15292. 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);
  15293. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15294. depthTexture._framebuffer = framebuffer;
  15295. depthTexture.baseWidth = width;
  15296. depthTexture.baseHeight = height;
  15297. depthTexture.width = width;
  15298. depthTexture.height = height;
  15299. depthTexture.isReady = true;
  15300. depthTexture.samples = 1;
  15301. depthTexture.generateMipMaps = generateMipMaps;
  15302. depthTexture.samplingMode = gl.NEAREST;
  15303. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15304. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15305. textures.push(depthTexture);
  15306. this._internalTexturesCache.push(depthTexture);
  15307. }
  15308. gl.drawBuffers(attachments);
  15309. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15310. this.bindUnboundFramebuffer(null);
  15311. this.resetTextureCache();
  15312. return textures;
  15313. };
  15314. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15315. if (samples === void 0) { samples = 1; }
  15316. var depthStencilBuffer = null;
  15317. var gl = this._gl;
  15318. // Create the depth/stencil buffer
  15319. if (generateStencilBuffer) {
  15320. depthStencilBuffer = gl.createRenderbuffer();
  15321. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15322. if (samples > 1) {
  15323. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15324. }
  15325. else {
  15326. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15327. }
  15328. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15329. }
  15330. else if (generateDepthBuffer) {
  15331. depthStencilBuffer = gl.createRenderbuffer();
  15332. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15333. if (samples > 1) {
  15334. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15335. }
  15336. else {
  15337. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15338. }
  15339. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15340. }
  15341. return depthStencilBuffer;
  15342. };
  15343. /**
  15344. * Updates the sample count of a render target texture
  15345. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15346. * @param texture defines the texture to update
  15347. * @param samples defines the sample count to set
  15348. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15349. */
  15350. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15351. if (this.webGLVersion < 2 || !texture) {
  15352. return 1;
  15353. }
  15354. if (texture.samples === samples) {
  15355. return samples;
  15356. }
  15357. var gl = this._gl;
  15358. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15359. // Dispose previous render buffers
  15360. if (texture._depthStencilBuffer) {
  15361. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15362. texture._depthStencilBuffer = null;
  15363. }
  15364. if (texture._MSAAFramebuffer) {
  15365. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15366. texture._MSAAFramebuffer = null;
  15367. }
  15368. if (texture._MSAARenderBuffer) {
  15369. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15370. texture._MSAARenderBuffer = null;
  15371. }
  15372. if (samples > 1) {
  15373. var framebuffer = gl.createFramebuffer();
  15374. if (!framebuffer) {
  15375. throw new Error("Unable to create multi sampled framebuffer");
  15376. }
  15377. texture._MSAAFramebuffer = framebuffer;
  15378. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15379. var colorRenderbuffer = gl.createRenderbuffer();
  15380. if (!colorRenderbuffer) {
  15381. throw new Error("Unable to create multi sampled framebuffer");
  15382. }
  15383. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15384. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15385. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15386. texture._MSAARenderBuffer = colorRenderbuffer;
  15387. }
  15388. else {
  15389. this.bindUnboundFramebuffer(texture._framebuffer);
  15390. }
  15391. texture.samples = samples;
  15392. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15393. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15394. this.bindUnboundFramebuffer(null);
  15395. return samples;
  15396. };
  15397. /**
  15398. * Update the sample count for a given multiple render target texture
  15399. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15400. * @param textures defines the textures to update
  15401. * @param samples defines the sample count to set
  15402. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15403. */
  15404. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15405. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15406. return 1;
  15407. }
  15408. if (textures[0].samples === samples) {
  15409. return samples;
  15410. }
  15411. var gl = this._gl;
  15412. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15413. // Dispose previous render buffers
  15414. if (textures[0]._depthStencilBuffer) {
  15415. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15416. textures[0]._depthStencilBuffer = null;
  15417. }
  15418. if (textures[0]._MSAAFramebuffer) {
  15419. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15420. textures[0]._MSAAFramebuffer = null;
  15421. }
  15422. for (var i = 0; i < textures.length; i++) {
  15423. if (textures[i]._MSAARenderBuffer) {
  15424. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15425. textures[i]._MSAARenderBuffer = null;
  15426. }
  15427. }
  15428. if (samples > 1) {
  15429. var framebuffer = gl.createFramebuffer();
  15430. if (!framebuffer) {
  15431. throw new Error("Unable to create multi sampled framebuffer");
  15432. }
  15433. this.bindUnboundFramebuffer(framebuffer);
  15434. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15435. var attachments = [];
  15436. for (var i = 0; i < textures.length; i++) {
  15437. var texture = textures[i];
  15438. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15439. var colorRenderbuffer = gl.createRenderbuffer();
  15440. if (!colorRenderbuffer) {
  15441. throw new Error("Unable to create multi sampled framebuffer");
  15442. }
  15443. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15444. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15445. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15446. texture._MSAAFramebuffer = framebuffer;
  15447. texture._MSAARenderBuffer = colorRenderbuffer;
  15448. texture.samples = samples;
  15449. texture._depthStencilBuffer = depthStencilBuffer;
  15450. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15451. attachments.push(attachment);
  15452. }
  15453. gl.drawBuffers(attachments);
  15454. }
  15455. else {
  15456. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15457. }
  15458. this.bindUnboundFramebuffer(null);
  15459. return samples;
  15460. };
  15461. /** @hidden */
  15462. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15463. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15464. };
  15465. /** @hidden */
  15466. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15467. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15468. };
  15469. /**
  15470. * Creates a new render target cube texture
  15471. * @param size defines the size of the texture
  15472. * @param options defines the options used to create the texture
  15473. * @returns a new render target cube texture stored in an InternalTexture
  15474. */
  15475. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15476. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15477. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15478. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15479. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15480. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15481. }
  15482. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15483. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15484. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15485. }
  15486. var gl = this._gl;
  15487. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15488. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15489. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15490. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15491. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15492. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15493. }
  15494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15495. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15496. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15497. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15498. for (var face = 0; face < 6; face++) {
  15499. 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);
  15500. }
  15501. // Create the framebuffer
  15502. var framebuffer = gl.createFramebuffer();
  15503. this.bindUnboundFramebuffer(framebuffer);
  15504. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15505. // MipMaps
  15506. if (fullOptions.generateMipMaps) {
  15507. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15508. }
  15509. // Unbind
  15510. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15511. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15512. this.bindUnboundFramebuffer(null);
  15513. texture._framebuffer = framebuffer;
  15514. texture.width = size;
  15515. texture.height = size;
  15516. texture.isReady = true;
  15517. texture.isCube = true;
  15518. texture.samples = 1;
  15519. texture.generateMipMaps = fullOptions.generateMipMaps;
  15520. texture.samplingMode = fullOptions.samplingMode;
  15521. texture.type = fullOptions.type;
  15522. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15523. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15524. this._internalTexturesCache.push(texture);
  15525. return texture;
  15526. };
  15527. /**
  15528. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15529. * @param rootUrl defines the url where the file to load is located
  15530. * @param scene defines the current scene
  15531. * @param scale defines scale to apply to the mip map selection
  15532. * @param offset defines offset to apply to the mip map selection
  15533. * @param onLoad defines an optional callback raised when the texture is loaded
  15534. * @param onError defines an optional callback raised if there is an issue to load the texture
  15535. * @param format defines the format of the data
  15536. * @param forcedExtension defines the extension to use to pick the right loader
  15537. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15538. * @returns the cube texture as an InternalTexture
  15539. */
  15540. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15541. var _this = this;
  15542. if (onLoad === void 0) { onLoad = null; }
  15543. if (onError === void 0) { onError = null; }
  15544. if (forcedExtension === void 0) { forcedExtension = null; }
  15545. if (createPolynomials === void 0) { createPolynomials = true; }
  15546. var callback = function (loadData) {
  15547. if (!loadData) {
  15548. if (onLoad) {
  15549. onLoad(null);
  15550. }
  15551. return;
  15552. }
  15553. var texture = loadData.texture;
  15554. if (!createPolynomials) {
  15555. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15556. }
  15557. else if (loadData.info.sphericalPolynomial) {
  15558. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15559. }
  15560. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15561. texture._lodGenerationScale = scale;
  15562. texture._lodGenerationOffset = offset;
  15563. if (_this._caps.textureLOD) {
  15564. // Do not add extra process if texture lod is supported.
  15565. if (onLoad) {
  15566. onLoad(texture);
  15567. }
  15568. return;
  15569. }
  15570. var mipSlices = 3;
  15571. var gl = _this._gl;
  15572. var width = loadData.width;
  15573. if (!width) {
  15574. return;
  15575. }
  15576. var textures = [];
  15577. for (var i = 0; i < mipSlices; i++) {
  15578. //compute LOD from even spacing in smoothness (matching shader calculation)
  15579. var smoothness = i / (mipSlices - 1);
  15580. var roughness = 1 - smoothness;
  15581. var minLODIndex = offset; // roughness = 0
  15582. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15583. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15584. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15585. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15586. glTextureFromLod.isCube = true;
  15587. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15592. if (loadData.isDDS) {
  15593. var info = loadData.info;
  15594. var data = loadData.data;
  15595. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15596. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15597. }
  15598. else {
  15599. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15600. }
  15601. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15602. // Wrap in a base texture for easy binding.
  15603. var lodTexture = new BABYLON.BaseTexture(scene);
  15604. lodTexture.isCube = true;
  15605. lodTexture._texture = glTextureFromLod;
  15606. glTextureFromLod.isReady = true;
  15607. textures.push(lodTexture);
  15608. }
  15609. texture._lodTextureHigh = textures[2];
  15610. texture._lodTextureMid = textures[1];
  15611. texture._lodTextureLow = textures[0];
  15612. if (onLoad) {
  15613. onLoad(texture);
  15614. }
  15615. };
  15616. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15617. };
  15618. /**
  15619. * Creates a cube texture
  15620. * @param rootUrl defines the url where the files to load is located
  15621. * @param scene defines the current scene
  15622. * @param files defines the list of files to load (1 per face)
  15623. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15624. * @param onLoad defines an optional callback raised when the texture is loaded
  15625. * @param onError defines an optional callback raised if there is an issue to load the texture
  15626. * @param format defines the format of the data
  15627. * @param forcedExtension defines the extension to use to pick the right loader
  15628. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15629. * @returns the cube texture as an InternalTexture
  15630. */
  15631. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15632. var _this = this;
  15633. if (onLoad === void 0) { onLoad = null; }
  15634. if (onError === void 0) { onError = null; }
  15635. if (forcedExtension === void 0) { forcedExtension = null; }
  15636. if (createPolynomials === void 0) { createPolynomials = false; }
  15637. var gl = this._gl;
  15638. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15639. texture.isCube = true;
  15640. texture.url = rootUrl;
  15641. texture.generateMipMaps = !noMipmap;
  15642. if (!this._doNotHandleContextLost) {
  15643. texture._extension = forcedExtension;
  15644. texture._files = files;
  15645. }
  15646. var isKTX = false;
  15647. var isDDS = false;
  15648. var lastDot = rootUrl.lastIndexOf('.');
  15649. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15650. if (this._textureFormatInUse) {
  15651. extension = this._textureFormatInUse;
  15652. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15653. isKTX = true;
  15654. }
  15655. else {
  15656. isDDS = (extension === ".dds");
  15657. }
  15658. var onerror = function (request, exception) {
  15659. if (onError && request) {
  15660. onError(request.status + " " + request.statusText, exception);
  15661. }
  15662. };
  15663. if (isKTX) {
  15664. this._loadFile(rootUrl, function (data) {
  15665. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15666. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15667. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15668. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15669. ktx.uploadLevels(_this._gl, !noMipmap);
  15670. _this.setCubeMapTextureParams(gl, loadMipmap);
  15671. texture.width = ktx.pixelWidth;
  15672. texture.height = ktx.pixelHeight;
  15673. texture.isReady = true;
  15674. }, undefined, undefined, true, onerror);
  15675. }
  15676. else if (isDDS) {
  15677. if (files && files.length === 6) {
  15678. this._cascadeLoadFiles(scene, function (imgs) {
  15679. var info;
  15680. var loadMipmap = false;
  15681. var width = 0;
  15682. for (var index = 0; index < imgs.length; index++) {
  15683. var data = imgs[index];
  15684. info = BABYLON.DDSTools.GetDDSInfo(data);
  15685. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15686. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15687. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15688. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15689. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15690. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15691. }
  15692. texture.width = info.width;
  15693. texture.height = info.height;
  15694. texture.type = info.textureType;
  15695. width = info.width;
  15696. }
  15697. _this.setCubeMapTextureParams(gl, loadMipmap);
  15698. texture.isReady = true;
  15699. if (onLoad) {
  15700. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15701. }
  15702. }, files, onError);
  15703. }
  15704. else {
  15705. this._loadFile(rootUrl, function (data) {
  15706. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15707. if (createPolynomials) {
  15708. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15709. }
  15710. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15711. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15712. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15713. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15714. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15715. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15716. }
  15717. _this.setCubeMapTextureParams(gl, loadMipmap);
  15718. texture.width = info.width;
  15719. texture.height = info.height;
  15720. texture.isReady = true;
  15721. texture.type = info.textureType;
  15722. if (onLoad) {
  15723. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15724. }
  15725. }, undefined, undefined, true, onerror);
  15726. }
  15727. }
  15728. else {
  15729. if (!files) {
  15730. throw new Error("Cannot load cubemap because files were not defined");
  15731. }
  15732. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15733. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15734. var height = width;
  15735. _this._prepareWorkingCanvas();
  15736. if (!_this._workingCanvas || !_this._workingContext) {
  15737. return;
  15738. }
  15739. _this._workingCanvas.width = width;
  15740. _this._workingCanvas.height = height;
  15741. var faces = [
  15742. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15743. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15744. ];
  15745. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15746. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15747. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15748. for (var index = 0; index < faces.length; index++) {
  15749. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15750. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15751. }
  15752. if (!noMipmap) {
  15753. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15754. }
  15755. _this.setCubeMapTextureParams(gl, !noMipmap);
  15756. texture.width = width;
  15757. texture.height = height;
  15758. texture.isReady = true;
  15759. if (format) {
  15760. texture.format = format;
  15761. }
  15762. texture.onLoadedObservable.notifyObservers(texture);
  15763. texture.onLoadedObservable.clear();
  15764. if (onLoad) {
  15765. onLoad();
  15766. }
  15767. }, files, onError);
  15768. }
  15769. this._internalTexturesCache.push(texture);
  15770. return texture;
  15771. };
  15772. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15777. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15778. // this.resetTextureCache();
  15779. };
  15780. /**
  15781. * Update a raw cube texture
  15782. * @param texture defines the texture to udpdate
  15783. * @param data defines the data to store
  15784. * @param format defines the data format
  15785. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15786. * @param invertY defines if data must be stored with Y axis inverted
  15787. * @param compression defines the compression used (null by default)
  15788. * @param level defines which level of the texture to update
  15789. */
  15790. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15791. if (compression === void 0) { compression = null; }
  15792. if (level === void 0) { level = 0; }
  15793. texture._bufferViewArray = data;
  15794. texture.format = format;
  15795. texture.type = type;
  15796. texture.invertY = invertY;
  15797. texture._compression = compression;
  15798. var gl = this._gl;
  15799. var textureType = this._getWebGLTextureType(type);
  15800. var internalFormat = this._getInternalFormat(format);
  15801. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15802. var needConversion = false;
  15803. if (internalFormat === gl.RGB) {
  15804. internalFormat = gl.RGBA;
  15805. needConversion = true;
  15806. }
  15807. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15808. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15809. if (texture.width % 4 !== 0) {
  15810. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15811. }
  15812. // Data are known to be in +X +Y +Z -X -Y -Z
  15813. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15814. var faceData = data[faceIndex];
  15815. if (compression) {
  15816. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15817. }
  15818. else {
  15819. if (needConversion) {
  15820. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15821. }
  15822. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15823. }
  15824. }
  15825. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15826. if (isPot && texture.generateMipMaps && level === 0) {
  15827. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15828. }
  15829. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15830. // this.resetTextureCache();
  15831. texture.isReady = true;
  15832. };
  15833. /**
  15834. * Creates a new raw cube texture
  15835. * @param data defines the array of data to use to create each face
  15836. * @param size defines the size of the textures
  15837. * @param format defines the format of the data
  15838. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15839. * @param generateMipMaps defines if the engine should generate the mip levels
  15840. * @param invertY defines if data must be stored with Y axis inverted
  15841. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15842. * @param compression defines the compression used (null by default)
  15843. * @returns the cube texture as an InternalTexture
  15844. */
  15845. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15846. if (compression === void 0) { compression = null; }
  15847. var gl = this._gl;
  15848. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15849. texture.isCube = true;
  15850. texture.generateMipMaps = generateMipMaps;
  15851. texture.format = format;
  15852. texture.type = type;
  15853. if (!this._doNotHandleContextLost) {
  15854. texture._bufferViewArray = data;
  15855. }
  15856. var textureType = this._getWebGLTextureType(type);
  15857. var internalFormat = this._getInternalFormat(format);
  15858. if (internalFormat === gl.RGB) {
  15859. internalFormat = gl.RGBA;
  15860. }
  15861. var width = size;
  15862. var height = width;
  15863. texture.width = width;
  15864. texture.height = height;
  15865. // Double check on POT to generate Mips.
  15866. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15867. if (!isPot) {
  15868. generateMipMaps = false;
  15869. }
  15870. // Upload data if needed. The texture won't be ready until then.
  15871. if (data) {
  15872. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15873. }
  15874. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15875. // Filters
  15876. if (data && generateMipMaps) {
  15877. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15878. }
  15879. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15882. }
  15883. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15886. }
  15887. else {
  15888. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15889. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15890. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15891. }
  15892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15894. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15895. return texture;
  15896. };
  15897. /**
  15898. * Creates a new raw cube texture from a specified url
  15899. * @param url defines the url where the data is located
  15900. * @param scene defines the current scene
  15901. * @param size defines the size of the textures
  15902. * @param format defines the format of the data
  15903. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15904. * @param noMipmap defines if the engine should avoid generating the mip levels
  15905. * @param callback defines a callback used to extract texture data from loaded data
  15906. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15907. * @param onLoad defines a callback called when texture is loaded
  15908. * @param onError defines a callback called if there is an error
  15909. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15910. * @param invertY defines if data must be stored with Y axis inverted
  15911. * @returns the cube texture as an InternalTexture
  15912. */
  15913. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15914. var _this = this;
  15915. if (onLoad === void 0) { onLoad = null; }
  15916. if (onError === void 0) { onError = null; }
  15917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15918. if (invertY === void 0) { invertY = false; }
  15919. var gl = this._gl;
  15920. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15921. scene._addPendingData(texture);
  15922. texture.url = url;
  15923. this._internalTexturesCache.push(texture);
  15924. var onerror = function (request, exception) {
  15925. scene._removePendingData(texture);
  15926. if (onError && request) {
  15927. onError(request.status + " " + request.statusText, exception);
  15928. }
  15929. };
  15930. var internalCallback = function (data) {
  15931. var width = texture.width;
  15932. var faceDataArrays = callback(data);
  15933. if (!faceDataArrays) {
  15934. return;
  15935. }
  15936. if (mipmapGenerator) {
  15937. var textureType = _this._getWebGLTextureType(type);
  15938. var internalFormat = _this._getInternalFormat(format);
  15939. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15940. var needConversion = false;
  15941. if (internalFormat === gl.RGB) {
  15942. internalFormat = gl.RGBA;
  15943. needConversion = true;
  15944. }
  15945. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15946. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15947. var mipData = mipmapGenerator(faceDataArrays);
  15948. for (var level = 0; level < mipData.length; level++) {
  15949. var mipSize = width >> level;
  15950. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15951. var mipFaceData = mipData[level][faceIndex];
  15952. if (needConversion) {
  15953. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15954. }
  15955. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15956. }
  15957. }
  15958. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15959. }
  15960. else {
  15961. texture.generateMipMaps = !noMipmap;
  15962. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15963. }
  15964. texture.isReady = true;
  15965. // this.resetTextureCache();
  15966. scene._removePendingData(texture);
  15967. if (onLoad) {
  15968. onLoad();
  15969. }
  15970. };
  15971. this._loadFile(url, function (data) {
  15972. internalCallback(data);
  15973. }, undefined, scene.database, true, onerror);
  15974. return texture;
  15975. };
  15976. ;
  15977. /**
  15978. * Update a raw 3D texture
  15979. * @param texture defines the texture to update
  15980. * @param data defines the data to store
  15981. * @param format defines the data format
  15982. * @param invertY defines if data must be stored with Y axis inverted
  15983. * @param compression defines the used compression (can be null)
  15984. */
  15985. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15986. if (compression === void 0) { compression = null; }
  15987. var internalFormat = this._getInternalFormat(format);
  15988. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15989. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15990. if (!this._doNotHandleContextLost) {
  15991. texture._bufferView = data;
  15992. texture.format = format;
  15993. texture.invertY = invertY;
  15994. texture._compression = compression;
  15995. }
  15996. if (texture.width % 4 !== 0) {
  15997. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15998. }
  15999. if (compression && data) {
  16000. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16001. }
  16002. else {
  16003. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16004. }
  16005. if (texture.generateMipMaps) {
  16006. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16007. }
  16008. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16009. // this.resetTextureCache();
  16010. texture.isReady = true;
  16011. };
  16012. /**
  16013. * Creates a new raw 3D texture
  16014. * @param data defines the data used to create the texture
  16015. * @param width defines the width of the texture
  16016. * @param height defines the height of the texture
  16017. * @param depth defines the depth of the texture
  16018. * @param format defines the format of the texture
  16019. * @param generateMipMaps defines if the engine must generate mip levels
  16020. * @param invertY defines if data must be stored with Y axis inverted
  16021. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16022. * @param compression defines the compressed used (can be null)
  16023. * @returns a new raw 3D texture (stored in an InternalTexture)
  16024. */
  16025. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16026. if (compression === void 0) { compression = null; }
  16027. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16028. texture.baseWidth = width;
  16029. texture.baseHeight = height;
  16030. texture.baseDepth = depth;
  16031. texture.width = width;
  16032. texture.height = height;
  16033. texture.depth = depth;
  16034. texture.format = format;
  16035. texture.generateMipMaps = generateMipMaps;
  16036. texture.samplingMode = samplingMode;
  16037. texture.is3D = true;
  16038. if (!this._doNotHandleContextLost) {
  16039. texture._bufferView = data;
  16040. }
  16041. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16042. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16043. // Filters
  16044. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16045. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16046. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16047. if (generateMipMaps) {
  16048. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16049. }
  16050. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16051. this._internalTexturesCache.push(texture);
  16052. return texture;
  16053. };
  16054. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16055. var gl = this._gl;
  16056. if (!gl) {
  16057. return;
  16058. }
  16059. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16060. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16061. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16062. if (!noMipmap && !isCompressed) {
  16063. gl.generateMipmap(gl.TEXTURE_2D);
  16064. }
  16065. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16066. // this.resetTextureCache();
  16067. if (scene) {
  16068. scene._removePendingData(texture);
  16069. }
  16070. texture.onLoadedObservable.notifyObservers(texture);
  16071. texture.onLoadedObservable.clear();
  16072. };
  16073. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16074. var _this = this;
  16075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16076. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16077. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16078. var gl = this._gl;
  16079. if (!gl) {
  16080. return;
  16081. }
  16082. if (!texture._webGLTexture) {
  16083. // this.resetTextureCache();
  16084. if (scene) {
  16085. scene._removePendingData(texture);
  16086. }
  16087. return;
  16088. }
  16089. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16090. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16091. texture.baseWidth = width;
  16092. texture.baseHeight = height;
  16093. texture.width = potWidth;
  16094. texture.height = potHeight;
  16095. texture.isReady = true;
  16096. if (processFunction(potWidth, potHeight, function () {
  16097. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16098. })) {
  16099. // Returning as texture needs extra async steps
  16100. return;
  16101. }
  16102. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16103. };
  16104. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16105. // Create new RGBA data container.
  16106. var rgbaData;
  16107. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16108. rgbaData = new Float32Array(width * height * 4);
  16109. }
  16110. else {
  16111. rgbaData = new Uint32Array(width * height * 4);
  16112. }
  16113. // Convert each pixel.
  16114. for (var x = 0; x < width; x++) {
  16115. for (var y = 0; y < height; y++) {
  16116. var index = (y * width + x) * 3;
  16117. var newIndex = (y * width + x) * 4;
  16118. // Map Old Value to new value.
  16119. rgbaData[newIndex + 0] = rgbData[index + 0];
  16120. rgbaData[newIndex + 1] = rgbData[index + 1];
  16121. rgbaData[newIndex + 2] = rgbData[index + 2];
  16122. // Add fully opaque alpha channel.
  16123. rgbaData[newIndex + 3] = 1;
  16124. }
  16125. }
  16126. return rgbaData;
  16127. };
  16128. /** @hidden */
  16129. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16130. var gl = this._gl;
  16131. if (texture._framebuffer) {
  16132. gl.deleteFramebuffer(texture._framebuffer);
  16133. texture._framebuffer = null;
  16134. }
  16135. if (texture._depthStencilBuffer) {
  16136. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16137. texture._depthStencilBuffer = null;
  16138. }
  16139. if (texture._MSAAFramebuffer) {
  16140. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16141. texture._MSAAFramebuffer = null;
  16142. }
  16143. if (texture._MSAARenderBuffer) {
  16144. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16145. texture._MSAARenderBuffer = null;
  16146. }
  16147. };
  16148. /** @hidden */
  16149. Engine.prototype._releaseTexture = function (texture) {
  16150. var gl = this._gl;
  16151. this._releaseFramebufferObjects(texture);
  16152. gl.deleteTexture(texture._webGLTexture);
  16153. // Unbind channels
  16154. this.unbindAllTextures();
  16155. var index = this._internalTexturesCache.indexOf(texture);
  16156. if (index !== -1) {
  16157. this._internalTexturesCache.splice(index, 1);
  16158. }
  16159. // Integrated fixed lod samplers.
  16160. if (texture._lodTextureHigh) {
  16161. texture._lodTextureHigh.dispose();
  16162. }
  16163. if (texture._lodTextureMid) {
  16164. texture._lodTextureMid.dispose();
  16165. }
  16166. if (texture._lodTextureLow) {
  16167. texture._lodTextureLow.dispose();
  16168. }
  16169. // Set output texture of post process to null if the texture has been released/disposed
  16170. this.scenes.forEach(function (scene) {
  16171. scene.postProcesses.forEach(function (postProcess) {
  16172. if (postProcess._outputTexture == texture) {
  16173. postProcess._outputTexture = null;
  16174. }
  16175. });
  16176. scene.cameras.forEach(function (camera) {
  16177. camera._postProcesses.forEach(function (postProcess) {
  16178. if (postProcess) {
  16179. if (postProcess._outputTexture == texture) {
  16180. postProcess._outputTexture = null;
  16181. }
  16182. }
  16183. });
  16184. });
  16185. });
  16186. };
  16187. Engine.prototype.setProgram = function (program) {
  16188. if (this._currentProgram !== program) {
  16189. this._gl.useProgram(program);
  16190. this._currentProgram = program;
  16191. }
  16192. };
  16193. /**
  16194. * Binds an effect to the webGL context
  16195. * @param effect defines the effect to bind
  16196. */
  16197. Engine.prototype.bindSamplers = function (effect) {
  16198. this.setProgram(effect.getProgram());
  16199. var samplers = effect.getSamplers();
  16200. for (var index = 0; index < samplers.length; index++) {
  16201. var uniform = effect.getUniform(samplers[index]);
  16202. if (uniform) {
  16203. this._boundUniforms[index] = uniform;
  16204. }
  16205. }
  16206. this._currentEffect = null;
  16207. };
  16208. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16209. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16210. return;
  16211. }
  16212. // Remove
  16213. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16214. // Bind last to it
  16215. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16216. // Bind to dummy
  16217. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16218. };
  16219. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16220. if (!internalTexture) {
  16221. return -1;
  16222. }
  16223. internalTexture._initialSlot = channel;
  16224. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16225. if (channel !== internalTexture._designatedSlot) {
  16226. this._textureCollisions.addCount(1, false);
  16227. }
  16228. }
  16229. else {
  16230. if (channel !== internalTexture._designatedSlot) {
  16231. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16232. return internalTexture._designatedSlot;
  16233. }
  16234. else {
  16235. // No slot for this texture, let's pick a new one (if we find a free slot)
  16236. if (this._nextFreeTextureSlots.length) {
  16237. return this._nextFreeTextureSlots[0];
  16238. }
  16239. // We need to recycle the oldest bound texture, sorry.
  16240. this._textureCollisions.addCount(1, false);
  16241. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16242. }
  16243. }
  16244. }
  16245. return channel;
  16246. };
  16247. Engine.prototype._linkTrackers = function (previous, next) {
  16248. previous.next = next;
  16249. next.previous = previous;
  16250. };
  16251. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16252. var currentSlot = internalTexture._designatedSlot;
  16253. if (currentSlot === -1) {
  16254. return -1;
  16255. }
  16256. internalTexture._designatedSlot = -1;
  16257. if (this.disableTextureBindingOptimization) {
  16258. return -1;
  16259. }
  16260. // Remove from bound list
  16261. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16262. // Free the slot
  16263. this._boundTexturesCache[currentSlot] = null;
  16264. this._nextFreeTextureSlots.push(currentSlot);
  16265. return currentSlot;
  16266. };
  16267. Engine.prototype._activateCurrentTexture = function () {
  16268. if (this._currentTextureChannel !== this._activeChannel) {
  16269. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16270. this._currentTextureChannel = this._activeChannel;
  16271. }
  16272. };
  16273. /** @hidden */
  16274. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16275. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16276. if (force === void 0) { force = false; }
  16277. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16278. this._activeChannel = texture._designatedSlot;
  16279. }
  16280. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16281. var isTextureForRendering = texture && texture._initialSlot > -1;
  16282. if (currentTextureBound !== texture || force) {
  16283. if (currentTextureBound) {
  16284. this._removeDesignatedSlot(currentTextureBound);
  16285. }
  16286. this._activateCurrentTexture();
  16287. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16288. this._boundTexturesCache[this._activeChannel] = texture;
  16289. if (texture) {
  16290. if (!this.disableTextureBindingOptimization) {
  16291. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16292. if (slotIndex > -1) {
  16293. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16294. }
  16295. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16296. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16297. }
  16298. texture._designatedSlot = this._activeChannel;
  16299. }
  16300. }
  16301. else if (forTextureDataUpdate) {
  16302. this._activateCurrentTexture();
  16303. }
  16304. if (isTextureForRendering && !forTextureDataUpdate) {
  16305. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16306. }
  16307. };
  16308. /** @hidden */
  16309. Engine.prototype._bindTexture = function (channel, texture) {
  16310. if (channel < 0) {
  16311. return;
  16312. }
  16313. if (texture) {
  16314. channel = this._getCorrectTextureChannel(channel, texture);
  16315. }
  16316. this._activeChannel = channel;
  16317. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16318. };
  16319. /**
  16320. * Sets a texture to the webGL context from a postprocess
  16321. * @param channel defines the channel to use
  16322. * @param postProcess defines the source postprocess
  16323. */
  16324. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16325. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16326. };
  16327. /**
  16328. * Binds the output of the passed in post process to the texture channel specified
  16329. * @param channel The channel the texture should be bound to
  16330. * @param postProcess The post process which's output should be bound
  16331. */
  16332. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16333. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16334. };
  16335. /**
  16336. * Unbind all textures from the webGL context
  16337. */
  16338. Engine.prototype.unbindAllTextures = function () {
  16339. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16340. this._activeChannel = channel;
  16341. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16342. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16343. if (this.webGLVersion > 1) {
  16344. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16345. }
  16346. }
  16347. };
  16348. /**
  16349. * Sets a texture to the according uniform.
  16350. * @param channel The texture channel
  16351. * @param uniform The uniform to set
  16352. * @param texture The texture to apply
  16353. */
  16354. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16355. if (channel < 0) {
  16356. return;
  16357. }
  16358. if (uniform) {
  16359. this._boundUniforms[channel] = uniform;
  16360. }
  16361. this._setTexture(channel, texture);
  16362. };
  16363. /**
  16364. * Sets a depth stencil texture from a render target to the according uniform.
  16365. * @param channel The texture channel
  16366. * @param uniform The uniform to set
  16367. * @param texture The render target texture containing the depth stencil texture to apply
  16368. */
  16369. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16370. if (channel < 0) {
  16371. return;
  16372. }
  16373. if (uniform) {
  16374. this._boundUniforms[channel] = uniform;
  16375. }
  16376. if (!texture || !texture.depthStencilTexture) {
  16377. this._setTexture(channel, null);
  16378. }
  16379. else {
  16380. this._setTexture(channel, texture, false, true);
  16381. }
  16382. };
  16383. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16384. var uniform = this._boundUniforms[sourceSlot];
  16385. if (uniform._currentState === destination) {
  16386. return;
  16387. }
  16388. this._gl.uniform1i(uniform, destination);
  16389. uniform._currentState = destination;
  16390. };
  16391. Engine.prototype._getTextureWrapMode = function (mode) {
  16392. switch (mode) {
  16393. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16394. return this._gl.REPEAT;
  16395. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16396. return this._gl.CLAMP_TO_EDGE;
  16397. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16398. return this._gl.MIRRORED_REPEAT;
  16399. }
  16400. return this._gl.REPEAT;
  16401. };
  16402. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16403. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16404. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16405. // Not ready?
  16406. if (!texture) {
  16407. if (this._boundTexturesCache[channel] != null) {
  16408. this._activeChannel = channel;
  16409. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16410. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16411. if (this.webGLVersion > 1) {
  16412. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16413. }
  16414. }
  16415. return false;
  16416. }
  16417. // Video
  16418. if (texture.video) {
  16419. this._activeChannel = channel;
  16420. texture.update();
  16421. }
  16422. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16423. texture.delayLoad();
  16424. return false;
  16425. }
  16426. var internalTexture;
  16427. if (depthStencilTexture) {
  16428. internalTexture = texture.depthStencilTexture;
  16429. }
  16430. else if (texture.isReady()) {
  16431. internalTexture = texture.getInternalTexture();
  16432. }
  16433. else if (texture.isCube) {
  16434. internalTexture = this.emptyCubeTexture;
  16435. }
  16436. else if (texture.is3D) {
  16437. internalTexture = this.emptyTexture3D;
  16438. }
  16439. else {
  16440. internalTexture = this.emptyTexture;
  16441. }
  16442. if (!isPartOfTextureArray) {
  16443. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16444. }
  16445. var needToBind = true;
  16446. if (this._boundTexturesCache[channel] === internalTexture) {
  16447. this._moveBoundTextureOnTop(internalTexture);
  16448. if (!isPartOfTextureArray) {
  16449. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16450. }
  16451. needToBind = false;
  16452. }
  16453. this._activeChannel = channel;
  16454. if (internalTexture && internalTexture.is3D) {
  16455. if (needToBind) {
  16456. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16457. }
  16458. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16459. internalTexture._cachedWrapU = texture.wrapU;
  16460. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16461. }
  16462. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16463. internalTexture._cachedWrapV = texture.wrapV;
  16464. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16465. }
  16466. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16467. internalTexture._cachedWrapR = texture.wrapR;
  16468. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16469. }
  16470. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16471. }
  16472. else if (internalTexture && internalTexture.isCube) {
  16473. if (needToBind) {
  16474. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16475. }
  16476. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16477. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16478. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16479. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16480. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16481. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16482. }
  16483. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16484. }
  16485. else {
  16486. if (needToBind) {
  16487. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16488. }
  16489. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16490. internalTexture._cachedWrapU = texture.wrapU;
  16491. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16492. }
  16493. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16494. internalTexture._cachedWrapV = texture.wrapV;
  16495. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16496. }
  16497. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16498. }
  16499. return true;
  16500. };
  16501. /**
  16502. * Sets an array of texture to the webGL context
  16503. * @param channel defines the channel where the texture array must be set
  16504. * @param uniform defines the associated uniform location
  16505. * @param textures defines the array of textures to bind
  16506. */
  16507. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16508. if (channel < 0 || !uniform) {
  16509. return;
  16510. }
  16511. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16512. this._textureUnits = new Int32Array(textures.length);
  16513. }
  16514. for (var i = 0; i < textures.length; i++) {
  16515. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16516. }
  16517. this._gl.uniform1iv(uniform, this._textureUnits);
  16518. for (var index = 0; index < textures.length; index++) {
  16519. this._setTexture(this._textureUnits[index], textures[index], true);
  16520. }
  16521. };
  16522. /** @hidden */
  16523. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16524. var internalTexture = texture.getInternalTexture();
  16525. if (!internalTexture) {
  16526. return;
  16527. }
  16528. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16529. var value = texture.anisotropicFilteringLevel;
  16530. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16531. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16532. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16533. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16534. }
  16535. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16536. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16537. internalTexture._cachedAnisotropicFilteringLevel = value;
  16538. }
  16539. };
  16540. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16541. this._bindTextureDirectly(target, texture, true, true);
  16542. this._gl.texParameterf(target, parameter, value);
  16543. };
  16544. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16545. if (texture) {
  16546. this._bindTextureDirectly(target, texture, true, true);
  16547. }
  16548. this._gl.texParameteri(target, parameter, value);
  16549. };
  16550. /**
  16551. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16552. * @param x defines the x coordinate of the rectangle where pixels must be read
  16553. * @param y defines the y coordinate of the rectangle where pixels must be read
  16554. * @param width defines the width of the rectangle where pixels must be read
  16555. * @param height defines the height of the rectangle where pixels must be read
  16556. * @returns a Uint8Array containing RGBA colors
  16557. */
  16558. Engine.prototype.readPixels = function (x, y, width, height) {
  16559. var data = new Uint8Array(height * width * 4);
  16560. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16561. return data;
  16562. };
  16563. /**
  16564. * Add an externaly attached data from its key.
  16565. * This method call will fail and return false, if such key already exists.
  16566. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16567. * @param key the unique key that identifies the data
  16568. * @param data the data object to associate to the key for this Engine instance
  16569. * @return true if no such key were already present and the data was added successfully, false otherwise
  16570. */
  16571. Engine.prototype.addExternalData = function (key, data) {
  16572. if (!this._externalData) {
  16573. this._externalData = new BABYLON.StringDictionary();
  16574. }
  16575. return this._externalData.add(key, data);
  16576. };
  16577. /**
  16578. * Get an externaly attached data from its key
  16579. * @param key the unique key that identifies the data
  16580. * @return the associated data, if present (can be null), or undefined if not present
  16581. */
  16582. Engine.prototype.getExternalData = function (key) {
  16583. if (!this._externalData) {
  16584. this._externalData = new BABYLON.StringDictionary();
  16585. }
  16586. return this._externalData.get(key);
  16587. };
  16588. /**
  16589. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16590. * @param key the unique key that identifies the data
  16591. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16592. * @return the associated data, can be null if the factory returned null.
  16593. */
  16594. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16595. if (!this._externalData) {
  16596. this._externalData = new BABYLON.StringDictionary();
  16597. }
  16598. return this._externalData.getOrAddWithFactory(key, factory);
  16599. };
  16600. /**
  16601. * Remove an externaly attached data from the Engine instance
  16602. * @param key the unique key that identifies the data
  16603. * @return true if the data was successfully removed, false if it doesn't exist
  16604. */
  16605. Engine.prototype.removeExternalData = function (key) {
  16606. if (!this._externalData) {
  16607. this._externalData = new BABYLON.StringDictionary();
  16608. }
  16609. return this._externalData.remove(key);
  16610. };
  16611. /**
  16612. * Unbind all vertex attributes from the webGL context
  16613. */
  16614. Engine.prototype.unbindAllAttributes = function () {
  16615. if (this._mustWipeVertexAttributes) {
  16616. this._mustWipeVertexAttributes = false;
  16617. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16618. this._gl.disableVertexAttribArray(i);
  16619. this._vertexAttribArraysEnabled[i] = false;
  16620. this._currentBufferPointers[i].active = false;
  16621. }
  16622. return;
  16623. }
  16624. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16625. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16626. continue;
  16627. }
  16628. this._gl.disableVertexAttribArray(i);
  16629. this._vertexAttribArraysEnabled[i] = false;
  16630. this._currentBufferPointers[i].active = false;
  16631. }
  16632. };
  16633. /**
  16634. * 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
  16635. */
  16636. Engine.prototype.releaseEffects = function () {
  16637. for (var name in this._compiledEffects) {
  16638. this._deleteProgram(this._compiledEffects[name]._program);
  16639. }
  16640. this._compiledEffects = {};
  16641. };
  16642. /**
  16643. * Dispose and release all associated resources
  16644. */
  16645. Engine.prototype.dispose = function () {
  16646. this.hideLoadingUI();
  16647. this.stopRenderLoop();
  16648. // Release postProcesses
  16649. while (this.postProcesses.length) {
  16650. this.postProcesses[0].dispose();
  16651. }
  16652. // Empty texture
  16653. if (this._emptyTexture) {
  16654. this._releaseTexture(this._emptyTexture);
  16655. this._emptyTexture = null;
  16656. }
  16657. if (this._emptyCubeTexture) {
  16658. this._releaseTexture(this._emptyCubeTexture);
  16659. this._emptyCubeTexture = null;
  16660. }
  16661. // Rescale PP
  16662. if (this._rescalePostProcess) {
  16663. this._rescalePostProcess.dispose();
  16664. }
  16665. // Release scenes
  16666. while (this.scenes.length) {
  16667. this.scenes[0].dispose();
  16668. }
  16669. // Release audio engine
  16670. if (Engine.audioEngine) {
  16671. Engine.audioEngine.dispose();
  16672. }
  16673. // Release effects
  16674. this.releaseEffects();
  16675. // Unbind
  16676. this.unbindAllAttributes();
  16677. this._boundUniforms = [];
  16678. if (this._dummyFramebuffer) {
  16679. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16680. }
  16681. //WebVR
  16682. this.disableVR();
  16683. // Events
  16684. if (BABYLON.Tools.IsWindowObjectExist()) {
  16685. window.removeEventListener("blur", this._onBlur);
  16686. window.removeEventListener("focus", this._onFocus);
  16687. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16688. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16689. if (this._renderingCanvas) {
  16690. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16691. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16692. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16693. if (!this._doNotHandleContextLost) {
  16694. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16695. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16696. }
  16697. }
  16698. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16699. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16700. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16701. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16702. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16703. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16704. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16705. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16706. if (this._onVrDisplayConnect) {
  16707. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16708. if (this._onVrDisplayDisconnect) {
  16709. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16710. }
  16711. if (this._onVrDisplayPresentChange) {
  16712. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16713. }
  16714. this._onVrDisplayConnect = null;
  16715. this._onVrDisplayDisconnect = null;
  16716. }
  16717. }
  16718. // Remove from Instances
  16719. var index = Engine.Instances.indexOf(this);
  16720. if (index >= 0) {
  16721. Engine.Instances.splice(index, 1);
  16722. }
  16723. this._workingCanvas = null;
  16724. this._workingContext = null;
  16725. this._currentBufferPointers = [];
  16726. this._renderingCanvas = null;
  16727. this._currentProgram = null;
  16728. this._bindedRenderFunction = null;
  16729. this.onResizeObservable.clear();
  16730. this.onCanvasBlurObservable.clear();
  16731. this.onCanvasFocusObservable.clear();
  16732. this.onCanvasPointerOutObservable.clear();
  16733. this.onBeginFrameObservable.clear();
  16734. this.onEndFrameObservable.clear();
  16735. BABYLON.Effect.ResetCache();
  16736. // Abort active requests
  16737. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16738. var request = _a[_i];
  16739. request.abort();
  16740. }
  16741. };
  16742. // Loading screen
  16743. /**
  16744. * Display the loading screen
  16745. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16746. */
  16747. Engine.prototype.displayLoadingUI = function () {
  16748. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16749. return;
  16750. }
  16751. var loadingScreen = this.loadingScreen;
  16752. if (loadingScreen) {
  16753. loadingScreen.displayLoadingUI();
  16754. }
  16755. };
  16756. /**
  16757. * Hide the loading screen
  16758. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16759. */
  16760. Engine.prototype.hideLoadingUI = function () {
  16761. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16762. return;
  16763. }
  16764. var loadingScreen = this.loadingScreen;
  16765. if (loadingScreen) {
  16766. loadingScreen.hideLoadingUI();
  16767. }
  16768. };
  16769. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16770. /**
  16771. * Gets the current loading screen object
  16772. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16773. */
  16774. get: function () {
  16775. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16776. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16777. return this._loadingScreen;
  16778. },
  16779. /**
  16780. * Sets the current loading screen object
  16781. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16782. */
  16783. set: function (loadingScreen) {
  16784. this._loadingScreen = loadingScreen;
  16785. },
  16786. enumerable: true,
  16787. configurable: true
  16788. });
  16789. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16790. /**
  16791. * Sets the current loading screen text
  16792. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16793. */
  16794. set: function (text) {
  16795. this.loadingScreen.loadingUIText = text;
  16796. },
  16797. enumerable: true,
  16798. configurable: true
  16799. });
  16800. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16801. /**
  16802. * Sets the current loading screen background color
  16803. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16804. */
  16805. set: function (color) {
  16806. this.loadingScreen.loadingUIBackgroundColor = color;
  16807. },
  16808. enumerable: true,
  16809. configurable: true
  16810. });
  16811. /**
  16812. * Attach a new callback raised when context lost event is fired
  16813. * @param callback defines the callback to call
  16814. */
  16815. Engine.prototype.attachContextLostEvent = function (callback) {
  16816. if (this._renderingCanvas) {
  16817. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16818. }
  16819. };
  16820. /**
  16821. * Attach a new callback raised when context restored event is fired
  16822. * @param callback defines the callback to call
  16823. */
  16824. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16825. if (this._renderingCanvas) {
  16826. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16827. }
  16828. };
  16829. /**
  16830. * Gets the source code of the vertex shader associated with a specific webGL program
  16831. * @param program defines the program to use
  16832. * @returns a string containing the source code of the vertex shader associated with the program
  16833. */
  16834. Engine.prototype.getVertexShaderSource = function (program) {
  16835. var shaders = this._gl.getAttachedShaders(program);
  16836. if (!shaders) {
  16837. return null;
  16838. }
  16839. return this._gl.getShaderSource(shaders[0]);
  16840. };
  16841. /**
  16842. * Gets the source code of the fragment shader associated with a specific webGL program
  16843. * @param program defines the program to use
  16844. * @returns a string containing the source code of the fragment shader associated with the program
  16845. */
  16846. Engine.prototype.getFragmentShaderSource = function (program) {
  16847. var shaders = this._gl.getAttachedShaders(program);
  16848. if (!shaders) {
  16849. return null;
  16850. }
  16851. return this._gl.getShaderSource(shaders[1]);
  16852. };
  16853. /**
  16854. * Get the current error code of the webGL context
  16855. * @returns the error code
  16856. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16857. */
  16858. Engine.prototype.getError = function () {
  16859. return this._gl.getError();
  16860. };
  16861. // FPS
  16862. /**
  16863. * Gets the current framerate
  16864. * @returns a number representing the framerate
  16865. */
  16866. Engine.prototype.getFps = function () {
  16867. return this._fps;
  16868. };
  16869. /**
  16870. * Gets the time spent between current and previous frame
  16871. * @returns a number representing the delta time in ms
  16872. */
  16873. Engine.prototype.getDeltaTime = function () {
  16874. return this._deltaTime;
  16875. };
  16876. Engine.prototype._measureFps = function () {
  16877. this._performanceMonitor.sampleFrame();
  16878. this._fps = this._performanceMonitor.averageFPS;
  16879. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16880. };
  16881. /** @hidden */
  16882. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16883. if (faceIndex === void 0) { faceIndex = -1; }
  16884. var gl = this._gl;
  16885. if (!this._dummyFramebuffer) {
  16886. var dummy = gl.createFramebuffer();
  16887. if (!dummy) {
  16888. throw new Error("Unable to create dummy framebuffer");
  16889. }
  16890. this._dummyFramebuffer = dummy;
  16891. }
  16892. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16893. if (faceIndex > -1) {
  16894. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16895. }
  16896. else {
  16897. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16898. }
  16899. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16900. var buffer;
  16901. switch (readType) {
  16902. case gl.UNSIGNED_BYTE:
  16903. buffer = new Uint8Array(4 * width * height);
  16904. readType = gl.UNSIGNED_BYTE;
  16905. break;
  16906. default:
  16907. buffer = new Float32Array(4 * width * height);
  16908. readType = gl.FLOAT;
  16909. break;
  16910. }
  16911. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16912. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16913. return buffer;
  16914. };
  16915. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16916. if (this._webGLVersion > 1) {
  16917. return this._caps.colorBufferFloat;
  16918. }
  16919. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16920. };
  16921. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16922. if (this._webGLVersion > 1) {
  16923. return this._caps.colorBufferFloat;
  16924. }
  16925. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16926. };
  16927. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16928. Engine.prototype._canRenderToFramebuffer = function (type) {
  16929. var gl = this._gl;
  16930. //clear existing errors
  16931. while (gl.getError() !== gl.NO_ERROR) { }
  16932. var successful = true;
  16933. var texture = gl.createTexture();
  16934. gl.bindTexture(gl.TEXTURE_2D, texture);
  16935. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16938. var fb = gl.createFramebuffer();
  16939. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16940. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16941. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16942. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16943. successful = successful && (gl.getError() === gl.NO_ERROR);
  16944. //try render by clearing frame buffer's color buffer
  16945. if (successful) {
  16946. gl.clear(gl.COLOR_BUFFER_BIT);
  16947. successful = successful && (gl.getError() === gl.NO_ERROR);
  16948. }
  16949. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16950. if (successful) {
  16951. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16952. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16953. var readFormat = gl.RGBA;
  16954. var readType = gl.UNSIGNED_BYTE;
  16955. var buffer = new Uint8Array(4);
  16956. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16957. successful = successful && (gl.getError() === gl.NO_ERROR);
  16958. }
  16959. //clean up
  16960. gl.deleteTexture(texture);
  16961. gl.deleteFramebuffer(fb);
  16962. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16963. //clear accumulated errors
  16964. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16965. return successful;
  16966. };
  16967. /** @hidden */
  16968. Engine.prototype._getWebGLTextureType = function (type) {
  16969. if (type === Engine.TEXTURETYPE_FLOAT) {
  16970. return this._gl.FLOAT;
  16971. }
  16972. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16973. // Add Half Float Constant.
  16974. return this._gl.HALF_FLOAT_OES;
  16975. }
  16976. return this._gl.UNSIGNED_BYTE;
  16977. };
  16978. ;
  16979. Engine.prototype._getInternalFormat = function (format) {
  16980. var internalFormat = this._gl.RGBA;
  16981. switch (format) {
  16982. case Engine.TEXTUREFORMAT_ALPHA:
  16983. internalFormat = this._gl.ALPHA;
  16984. break;
  16985. case Engine.TEXTUREFORMAT_LUMINANCE:
  16986. internalFormat = this._gl.LUMINANCE;
  16987. break;
  16988. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16989. internalFormat = this._gl.LUMINANCE_ALPHA;
  16990. break;
  16991. case Engine.TEXTUREFORMAT_RGB:
  16992. case Engine.TEXTUREFORMAT_RGB32F:
  16993. internalFormat = this._gl.RGB;
  16994. break;
  16995. case Engine.TEXTUREFORMAT_RGBA:
  16996. case Engine.TEXTUREFORMAT_RGBA32F:
  16997. internalFormat = this._gl.RGBA;
  16998. break;
  16999. case Engine.TEXTUREFORMAT_R32F:
  17000. internalFormat = this._gl.RED;
  17001. break;
  17002. case Engine.TEXTUREFORMAT_RG32F:
  17003. internalFormat = this._gl.RG;
  17004. break;
  17005. }
  17006. return internalFormat;
  17007. };
  17008. /** @hidden */
  17009. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17010. if (this._webGLVersion === 1) {
  17011. if (format !== undefined) {
  17012. switch (format) {
  17013. case Engine.TEXTUREFORMAT_LUMINANCE:
  17014. return this._gl.LUMINANCE;
  17015. case Engine.TEXTUREFORMAT_ALPHA:
  17016. return this._gl.ALPHA;
  17017. }
  17018. }
  17019. return this._gl.RGBA;
  17020. }
  17021. if (type === Engine.TEXTURETYPE_FLOAT) {
  17022. if (format !== undefined) {
  17023. switch (format) {
  17024. case Engine.TEXTUREFORMAT_R32F:
  17025. return this._gl.R32F;
  17026. case Engine.TEXTUREFORMAT_RG32F:
  17027. return this._gl.RG32F;
  17028. case Engine.TEXTUREFORMAT_RGB32F:
  17029. return this._gl.RGB32F;
  17030. }
  17031. }
  17032. return this._gl.RGBA32F;
  17033. }
  17034. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17035. return this._gl.RGBA16F;
  17036. }
  17037. if (format !== undefined) {
  17038. switch (format) {
  17039. case Engine.TEXTUREFORMAT_LUMINANCE:
  17040. return this._gl.LUMINANCE;
  17041. case Engine.TEXTUREFORMAT_RGB:
  17042. return this._gl.RGB;
  17043. case Engine.TEXTUREFORMAT_ALPHA:
  17044. return this._gl.ALPHA;
  17045. }
  17046. }
  17047. return this._gl.RGBA;
  17048. };
  17049. ;
  17050. /** @hidden */
  17051. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17052. if (type === Engine.TEXTURETYPE_FLOAT) {
  17053. return this._gl.RGBA32F;
  17054. }
  17055. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17056. return this._gl.RGBA16F;
  17057. }
  17058. return this._gl.RGBA8;
  17059. };
  17060. ;
  17061. /**
  17062. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17063. * @return the new query
  17064. */
  17065. Engine.prototype.createQuery = function () {
  17066. return this._gl.createQuery();
  17067. };
  17068. /**
  17069. * Delete and release a webGL query
  17070. * @param query defines the query to delete
  17071. * @return the current engine
  17072. */
  17073. Engine.prototype.deleteQuery = function (query) {
  17074. this._gl.deleteQuery(query);
  17075. return this;
  17076. };
  17077. /**
  17078. * Check if a given query has resolved and got its value
  17079. * @param query defines the query to check
  17080. * @returns true if the query got its value
  17081. */
  17082. Engine.prototype.isQueryResultAvailable = function (query) {
  17083. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17084. };
  17085. /**
  17086. * Gets the value of a given query
  17087. * @param query defines the query to check
  17088. * @returns the value of the query
  17089. */
  17090. Engine.prototype.getQueryResult = function (query) {
  17091. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17092. };
  17093. /**
  17094. * Initiates an occlusion query
  17095. * @param algorithmType defines the algorithm to use
  17096. * @param query defines the query to use
  17097. * @returns the current engine
  17098. * @see http://doc.babylonjs.com/features/occlusionquery
  17099. */
  17100. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17101. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17102. this._gl.beginQuery(glAlgorithm, query);
  17103. return this;
  17104. };
  17105. /**
  17106. * Ends an occlusion query
  17107. * @see http://doc.babylonjs.com/features/occlusionquery
  17108. * @param algorithmType defines the algorithm to use
  17109. * @returns the current engine
  17110. */
  17111. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17112. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17113. this._gl.endQuery(glAlgorithm);
  17114. return this;
  17115. };
  17116. /* Time queries */
  17117. Engine.prototype._createTimeQuery = function () {
  17118. var timerQuery = this._caps.timerQuery;
  17119. if (timerQuery.createQueryEXT) {
  17120. return timerQuery.createQueryEXT();
  17121. }
  17122. return this.createQuery();
  17123. };
  17124. Engine.prototype._deleteTimeQuery = function (query) {
  17125. var timerQuery = this._caps.timerQuery;
  17126. if (timerQuery.deleteQueryEXT) {
  17127. timerQuery.deleteQueryEXT(query);
  17128. return;
  17129. }
  17130. this.deleteQuery(query);
  17131. };
  17132. Engine.prototype._getTimeQueryResult = function (query) {
  17133. var timerQuery = this._caps.timerQuery;
  17134. if (timerQuery.getQueryObjectEXT) {
  17135. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17136. }
  17137. return this.getQueryResult(query);
  17138. };
  17139. Engine.prototype._getTimeQueryAvailability = function (query) {
  17140. var timerQuery = this._caps.timerQuery;
  17141. if (timerQuery.getQueryObjectEXT) {
  17142. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17143. }
  17144. return this.isQueryResultAvailable(query);
  17145. };
  17146. /**
  17147. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17148. * Please note that only one query can be issued at a time
  17149. * @returns a time token used to track the time span
  17150. */
  17151. Engine.prototype.startTimeQuery = function () {
  17152. var timerQuery = this._caps.timerQuery;
  17153. if (!timerQuery) {
  17154. return null;
  17155. }
  17156. var token = new BABYLON._TimeToken();
  17157. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17158. if (this._caps.canUseTimestampForTimerQuery) {
  17159. token._startTimeQuery = this._createTimeQuery();
  17160. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17161. }
  17162. else {
  17163. if (this._currentNonTimestampToken) {
  17164. return this._currentNonTimestampToken;
  17165. }
  17166. token._timeElapsedQuery = this._createTimeQuery();
  17167. if (timerQuery.beginQueryEXT) {
  17168. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17169. }
  17170. else {
  17171. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17172. }
  17173. this._currentNonTimestampToken = token;
  17174. }
  17175. return token;
  17176. };
  17177. /**
  17178. * Ends a time query
  17179. * @param token defines the token used to measure the time span
  17180. * @returns the time spent (in ns)
  17181. */
  17182. Engine.prototype.endTimeQuery = function (token) {
  17183. var timerQuery = this._caps.timerQuery;
  17184. if (!timerQuery || !token) {
  17185. return -1;
  17186. }
  17187. if (this._caps.canUseTimestampForTimerQuery) {
  17188. if (!token._startTimeQuery) {
  17189. return -1;
  17190. }
  17191. if (!token._endTimeQuery) {
  17192. token._endTimeQuery = this._createTimeQuery();
  17193. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17194. }
  17195. }
  17196. else if (!token._timeElapsedQueryEnded) {
  17197. if (!token._timeElapsedQuery) {
  17198. return -1;
  17199. }
  17200. if (timerQuery.endQueryEXT) {
  17201. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17202. }
  17203. else {
  17204. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17205. }
  17206. token._timeElapsedQueryEnded = true;
  17207. }
  17208. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17209. var available = false;
  17210. if (token._endTimeQuery) {
  17211. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17212. }
  17213. else if (token._timeElapsedQuery) {
  17214. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17215. }
  17216. if (available && !disjoint) {
  17217. var result = 0;
  17218. if (this._caps.canUseTimestampForTimerQuery) {
  17219. if (!token._startTimeQuery || !token._endTimeQuery) {
  17220. return -1;
  17221. }
  17222. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17223. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17224. result = timeEnd - timeStart;
  17225. this._deleteTimeQuery(token._startTimeQuery);
  17226. this._deleteTimeQuery(token._endTimeQuery);
  17227. token._startTimeQuery = null;
  17228. token._endTimeQuery = null;
  17229. }
  17230. else {
  17231. if (!token._timeElapsedQuery) {
  17232. return -1;
  17233. }
  17234. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17235. this._deleteTimeQuery(token._timeElapsedQuery);
  17236. token._timeElapsedQuery = null;
  17237. token._timeElapsedQueryEnded = false;
  17238. this._currentNonTimestampToken = null;
  17239. }
  17240. return result;
  17241. }
  17242. return -1;
  17243. };
  17244. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17245. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17246. };
  17247. // Transform feedback
  17248. /**
  17249. * Creates a webGL transform feedback object
  17250. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17251. * @returns the webGL transform feedback object
  17252. */
  17253. Engine.prototype.createTransformFeedback = function () {
  17254. return this._gl.createTransformFeedback();
  17255. };
  17256. /**
  17257. * Delete a webGL transform feedback object
  17258. * @param value defines the webGL transform feedback object to delete
  17259. */
  17260. Engine.prototype.deleteTransformFeedback = function (value) {
  17261. this._gl.deleteTransformFeedback(value);
  17262. };
  17263. /**
  17264. * Bind a webGL transform feedback object to the webgl context
  17265. * @param value defines the webGL transform feedback object to bind
  17266. */
  17267. Engine.prototype.bindTransformFeedback = function (value) {
  17268. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17269. };
  17270. /**
  17271. * Begins a transform feedback operation
  17272. * @param usePoints defines if points or triangles must be used
  17273. */
  17274. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17275. if (usePoints === void 0) { usePoints = true; }
  17276. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17277. };
  17278. /**
  17279. * Ends a transform feedback operation
  17280. */
  17281. Engine.prototype.endTransformFeedback = function () {
  17282. this._gl.endTransformFeedback();
  17283. };
  17284. /**
  17285. * Specify the varyings to use with transform feedback
  17286. * @param program defines the associated webGL program
  17287. * @param value defines the list of strings representing the varying names
  17288. */
  17289. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17290. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17291. };
  17292. /**
  17293. * Bind a webGL buffer for a transform feedback operation
  17294. * @param value defines the webGL buffer to bind
  17295. */
  17296. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17297. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17298. };
  17299. /** @hidden */
  17300. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17301. var _this = this;
  17302. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17303. this._activeRequests.push(request);
  17304. request.onCompleteObservable.add(function (request) {
  17305. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17306. });
  17307. return request;
  17308. };
  17309. /** @hidden */
  17310. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17311. var _this = this;
  17312. return new Promise(function (resolve, reject) {
  17313. _this._loadFile(url, function (data) {
  17314. resolve(data);
  17315. }, undefined, database, useArrayBuffer, function (request, exception) {
  17316. reject(exception);
  17317. });
  17318. });
  17319. };
  17320. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17321. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17322. var onload = function (data) {
  17323. loadedFiles[index] = data;
  17324. loadedFiles._internalCount++;
  17325. if (loadedFiles._internalCount === 6) {
  17326. onfinish(loadedFiles);
  17327. }
  17328. };
  17329. var onerror = function (request, exception) {
  17330. if (onErrorCallBack && request) {
  17331. onErrorCallBack(request.status + " " + request.statusText, exception);
  17332. }
  17333. };
  17334. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17335. };
  17336. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17337. if (onError === void 0) { onError = null; }
  17338. var loadedFiles = [];
  17339. loadedFiles._internalCount = 0;
  17340. for (var index = 0; index < 6; index++) {
  17341. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17342. }
  17343. };
  17344. // Statics
  17345. /**
  17346. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17347. * @returns true if the engine can be created
  17348. * @ignorenaming
  17349. */
  17350. Engine.isSupported = function () {
  17351. try {
  17352. var tempcanvas = document.createElement("canvas");
  17353. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17354. return gl != null && !!window.WebGLRenderingContext;
  17355. }
  17356. catch (e) {
  17357. return false;
  17358. }
  17359. };
  17360. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17361. Engine.ExceptionList = [
  17362. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17363. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17364. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17365. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17366. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17367. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17368. ];
  17369. /** Gets the list of created engines */
  17370. Engine.Instances = new Array();
  17371. // Const statics
  17372. Engine._ALPHA_DISABLE = 0;
  17373. Engine._ALPHA_ADD = 1;
  17374. Engine._ALPHA_COMBINE = 2;
  17375. Engine._ALPHA_SUBTRACT = 3;
  17376. Engine._ALPHA_MULTIPLY = 4;
  17377. Engine._ALPHA_MAXIMIZED = 5;
  17378. Engine._ALPHA_ONEONE = 6;
  17379. Engine._ALPHA_PREMULTIPLIED = 7;
  17380. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17381. Engine._ALPHA_INTERPOLATE = 9;
  17382. Engine._ALPHA_SCREENMODE = 10;
  17383. Engine._DELAYLOADSTATE_NONE = 0;
  17384. Engine._DELAYLOADSTATE_LOADED = 1;
  17385. Engine._DELAYLOADSTATE_LOADING = 2;
  17386. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17387. Engine._TEXTUREFORMAT_ALPHA = 0;
  17388. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17389. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17390. Engine._TEXTUREFORMAT_RGB = 4;
  17391. Engine._TEXTUREFORMAT_RGBA = 5;
  17392. Engine._TEXTUREFORMAT_R32F = 6;
  17393. Engine._TEXTUREFORMAT_RG32F = 7;
  17394. Engine._TEXTUREFORMAT_RGB32F = 8;
  17395. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17396. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17397. Engine._TEXTURETYPE_FLOAT = 1;
  17398. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17399. // Depht or Stencil test Constants.
  17400. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17401. 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.
  17402. 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.
  17403. 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.
  17404. 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.
  17405. 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.
  17406. 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.
  17407. 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.
  17408. // Stencil Actions Constants.
  17409. Engine._KEEP = 0x1E00;
  17410. Engine._REPLACE = 0x1E01;
  17411. Engine._INCR = 0x1E02;
  17412. Engine._DECR = 0x1E03;
  17413. Engine._INVERT = 0x150A;
  17414. Engine._INCR_WRAP = 0x8507;
  17415. Engine._DECR_WRAP = 0x8508;
  17416. // Texture rescaling mode
  17417. Engine._SCALEMODE_FLOOR = 1;
  17418. Engine._SCALEMODE_NEAREST = 2;
  17419. Engine._SCALEMODE_CEILING = 3;
  17420. // Updatable statics so stick with vars here
  17421. /**
  17422. * Gets or sets the epsilon value used by collision engine
  17423. */
  17424. Engine.CollisionsEpsilon = 0.001;
  17425. /**
  17426. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17427. */
  17428. Engine.CodeRepository = "src/";
  17429. /**
  17430. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17431. */
  17432. Engine.ShadersRepository = "src/Shaders/";
  17433. return Engine;
  17434. }());
  17435. BABYLON.Engine = Engine;
  17436. })(BABYLON || (BABYLON = {}));
  17437. //# sourceMappingURL=babylon.engine.js.map
  17438. var BABYLON;
  17439. (function (BABYLON) {
  17440. /**
  17441. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17442. */
  17443. var Node = /** @class */ (function () {
  17444. /**
  17445. * Creates a new Node
  17446. * @param {string} name - the name and id to be given to this node
  17447. * @param {BABYLON.Scene} the scene this node will be added to
  17448. */
  17449. function Node(name, scene) {
  17450. if (scene === void 0) { scene = null; }
  17451. /**
  17452. * Gets or sets a string used to store user defined state for the node
  17453. */
  17454. this.state = "";
  17455. /**
  17456. * Gets or sets an object used to store user defined information for the node
  17457. */
  17458. this.metadata = null;
  17459. /**
  17460. * Gets or sets a boolean used to define if the node must be serialized
  17461. */
  17462. this.doNotSerialize = false;
  17463. /** @hidden */
  17464. this._isDisposed = false;
  17465. /**
  17466. * Gets a list of Animations associated with the node
  17467. */
  17468. this.animations = new Array();
  17469. this._ranges = {};
  17470. this._isEnabled = true;
  17471. this._isReady = true;
  17472. /** @hidden */
  17473. this._currentRenderId = -1;
  17474. this._parentRenderId = -1;
  17475. this._childRenderId = -1;
  17476. this._animationPropertiesOverride = null;
  17477. /**
  17478. * An event triggered when the mesh is disposed
  17479. */
  17480. this.onDisposeObservable = new BABYLON.Observable();
  17481. // Behaviors
  17482. this._behaviors = new Array();
  17483. this.name = name;
  17484. this.id = name;
  17485. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17486. this.uniqueId = this._scene.getUniqueId();
  17487. this._initCache();
  17488. }
  17489. /**
  17490. * Gets a boolean indicating if the node has been disposed
  17491. * @returns true if the node was disposed
  17492. */
  17493. Node.prototype.isDisposed = function () {
  17494. return this._isDisposed;
  17495. };
  17496. Object.defineProperty(Node.prototype, "parent", {
  17497. get: function () {
  17498. return this._parentNode;
  17499. },
  17500. /**
  17501. * Gets or sets the parent of the node
  17502. */
  17503. set: function (parent) {
  17504. if (this._parentNode === parent) {
  17505. return;
  17506. }
  17507. // Remove self from list of children of parent
  17508. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17509. var index = this._parentNode._children.indexOf(this);
  17510. if (index !== -1) {
  17511. this._parentNode._children.splice(index, 1);
  17512. }
  17513. }
  17514. // Store new parent
  17515. this._parentNode = parent;
  17516. // Add as child to new parent
  17517. if (this._parentNode) {
  17518. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17519. this._parentNode._children = new Array();
  17520. }
  17521. this._parentNode._children.push(this);
  17522. }
  17523. },
  17524. enumerable: true,
  17525. configurable: true
  17526. });
  17527. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17528. /**
  17529. * Gets or sets the animation properties override
  17530. */
  17531. get: function () {
  17532. if (!this._animationPropertiesOverride) {
  17533. return this._scene.animationPropertiesOverride;
  17534. }
  17535. return this._animationPropertiesOverride;
  17536. },
  17537. set: function (value) {
  17538. this._animationPropertiesOverride = value;
  17539. },
  17540. enumerable: true,
  17541. configurable: true
  17542. });
  17543. /**
  17544. * Gets a string idenfifying the name of the class
  17545. * @returns "Node" string
  17546. */
  17547. Node.prototype.getClassName = function () {
  17548. return "Node";
  17549. };
  17550. Object.defineProperty(Node.prototype, "onDispose", {
  17551. /**
  17552. * Sets a callback that will be raised when the node will be disposed
  17553. */
  17554. set: function (callback) {
  17555. if (this._onDisposeObserver) {
  17556. this.onDisposeObservable.remove(this._onDisposeObserver);
  17557. }
  17558. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17559. },
  17560. enumerable: true,
  17561. configurable: true
  17562. });
  17563. /**
  17564. * Gets the scene of the node
  17565. * @returns a {BABYLON.Scene}
  17566. */
  17567. Node.prototype.getScene = function () {
  17568. return this._scene;
  17569. };
  17570. /**
  17571. * Gets the engine of the node
  17572. * @returns a {BABYLON.Engine}
  17573. */
  17574. Node.prototype.getEngine = function () {
  17575. return this._scene.getEngine();
  17576. };
  17577. /**
  17578. * Attach a behavior to the node
  17579. * @see http://doc.babylonjs.com/features/behaviour
  17580. * @param behavior defines the behavior to attach
  17581. * @returns the current Node
  17582. */
  17583. Node.prototype.addBehavior = function (behavior) {
  17584. var _this = this;
  17585. var index = this._behaviors.indexOf(behavior);
  17586. if (index !== -1) {
  17587. return this;
  17588. }
  17589. behavior.init();
  17590. if (this._scene.isLoading) {
  17591. // We defer the attach when the scene will be loaded
  17592. this._scene.onDataLoadedObservable.addOnce(function () {
  17593. behavior.attach(_this);
  17594. });
  17595. }
  17596. else {
  17597. behavior.attach(this);
  17598. }
  17599. this._behaviors.push(behavior);
  17600. return this;
  17601. };
  17602. /**
  17603. * Remove an attached behavior
  17604. * @see http://doc.babylonjs.com/features/behaviour
  17605. * @param behavior defines the behavior to attach
  17606. * @returns the current Node
  17607. */
  17608. Node.prototype.removeBehavior = function (behavior) {
  17609. var index = this._behaviors.indexOf(behavior);
  17610. if (index === -1) {
  17611. return this;
  17612. }
  17613. this._behaviors[index].detach();
  17614. this._behaviors.splice(index, 1);
  17615. return this;
  17616. };
  17617. Object.defineProperty(Node.prototype, "behaviors", {
  17618. /**
  17619. * Gets the list of attached behaviors
  17620. * @see http://doc.babylonjs.com/features/behaviour
  17621. */
  17622. get: function () {
  17623. return this._behaviors;
  17624. },
  17625. enumerable: true,
  17626. configurable: true
  17627. });
  17628. /**
  17629. * Gets an attached behavior by name
  17630. * @param name defines the name of the behavior to look for
  17631. * @see http://doc.babylonjs.com/features/behaviour
  17632. * @returns null if behavior was not found else the requested behavior
  17633. */
  17634. Node.prototype.getBehaviorByName = function (name) {
  17635. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17636. var behavior = _a[_i];
  17637. if (behavior.name === name) {
  17638. return behavior;
  17639. }
  17640. }
  17641. return null;
  17642. };
  17643. /**
  17644. * Returns the world matrix of the node
  17645. * @returns a matrix containing the node's world matrix
  17646. */
  17647. Node.prototype.getWorldMatrix = function () {
  17648. return BABYLON.Matrix.Identity();
  17649. };
  17650. /** @hidden */
  17651. Node.prototype._getWorldMatrixDeterminant = function () {
  17652. return 1;
  17653. };
  17654. // override it in derived class if you add new variables to the cache
  17655. // and call the parent class method
  17656. /** @hidden */
  17657. Node.prototype._initCache = function () {
  17658. this._cache = {};
  17659. this._cache.parent = undefined;
  17660. };
  17661. /** @hidden */
  17662. Node.prototype.updateCache = function (force) {
  17663. if (!force && this.isSynchronized())
  17664. return;
  17665. this._cache.parent = this.parent;
  17666. this._updateCache();
  17667. };
  17668. // override it in derived class if you add new variables to the cache
  17669. // and call the parent class method if !ignoreParentClass
  17670. /** @hidden */
  17671. Node.prototype._updateCache = function (ignoreParentClass) {
  17672. };
  17673. // override it in derived class if you add new variables to the cache
  17674. /** @hidden */
  17675. Node.prototype._isSynchronized = function () {
  17676. return true;
  17677. };
  17678. /** @hidden */
  17679. Node.prototype._markSyncedWithParent = function () {
  17680. if (this.parent) {
  17681. this._parentRenderId = this.parent._childRenderId;
  17682. }
  17683. };
  17684. /** @hidden */
  17685. Node.prototype.isSynchronizedWithParent = function () {
  17686. if (!this.parent) {
  17687. return true;
  17688. }
  17689. if (this._parentRenderId !== this.parent._childRenderId) {
  17690. return false;
  17691. }
  17692. return this.parent.isSynchronized();
  17693. };
  17694. /** @hidden */
  17695. Node.prototype.isSynchronized = function (updateCache) {
  17696. var check = this.hasNewParent();
  17697. check = check || !this.isSynchronizedWithParent();
  17698. check = check || !this._isSynchronized();
  17699. if (updateCache)
  17700. this.updateCache(true);
  17701. return !check;
  17702. };
  17703. /** @hidden */
  17704. Node.prototype.hasNewParent = function (update) {
  17705. if (this._cache.parent === this.parent)
  17706. return false;
  17707. if (update)
  17708. this._cache.parent = this.parent;
  17709. return true;
  17710. };
  17711. /**
  17712. * Is this node ready to be used/rendered
  17713. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17714. * @return true if the node is ready
  17715. */
  17716. Node.prototype.isReady = function (completeCheck) {
  17717. if (completeCheck === void 0) { completeCheck = false; }
  17718. return this._isReady;
  17719. };
  17720. /**
  17721. * Is this node enabled?
  17722. * 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
  17723. * @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
  17724. * @return whether this node (and its parent) is enabled
  17725. */
  17726. Node.prototype.isEnabled = function (checkAncestors) {
  17727. if (checkAncestors === void 0) { checkAncestors = true; }
  17728. if (checkAncestors === false) {
  17729. return this._isEnabled;
  17730. }
  17731. if (this._isEnabled === false) {
  17732. return false;
  17733. }
  17734. if (this.parent !== undefined && this.parent !== null) {
  17735. return this.parent.isEnabled(checkAncestors);
  17736. }
  17737. return true;
  17738. };
  17739. /**
  17740. * Set the enabled state of this node
  17741. * @param value defines the new enabled state
  17742. */
  17743. Node.prototype.setEnabled = function (value) {
  17744. this._isEnabled = value;
  17745. };
  17746. /**
  17747. * Is this node a descendant of the given node?
  17748. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17749. * @param ancestor defines the parent node to inspect
  17750. * @returns a boolean indicating if this node is a descendant of the given node
  17751. */
  17752. Node.prototype.isDescendantOf = function (ancestor) {
  17753. if (this.parent) {
  17754. if (this.parent === ancestor) {
  17755. return true;
  17756. }
  17757. return this.parent.isDescendantOf(ancestor);
  17758. }
  17759. return false;
  17760. };
  17761. /** @hidden */
  17762. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17763. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17764. if (!this._children) {
  17765. return;
  17766. }
  17767. for (var index = 0; index < this._children.length; index++) {
  17768. var item = this._children[index];
  17769. if (!predicate || predicate(item)) {
  17770. results.push(item);
  17771. }
  17772. if (!directDescendantsOnly) {
  17773. item._getDescendants(results, false, predicate);
  17774. }
  17775. }
  17776. };
  17777. /**
  17778. * Will return all nodes that have this node as ascendant
  17779. * @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
  17780. * @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
  17781. * @return all children nodes of all types
  17782. */
  17783. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17784. var results = new Array();
  17785. this._getDescendants(results, directDescendantsOnly, predicate);
  17786. return results;
  17787. };
  17788. /**
  17789. * Get all child-meshes of this node
  17790. * @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
  17791. * @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
  17792. * @returns an array of {BABYLON.AbstractMesh}
  17793. */
  17794. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17795. var results = [];
  17796. this._getDescendants(results, directDescendantsOnly, function (node) {
  17797. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17798. });
  17799. return results;
  17800. };
  17801. /**
  17802. * Get all child-transformNodes of this node
  17803. * @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
  17804. * @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
  17805. * @returns an array of {BABYLON.TransformNode}
  17806. */
  17807. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17808. var results = [];
  17809. this._getDescendants(results, directDescendantsOnly, function (node) {
  17810. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17811. });
  17812. return results;
  17813. };
  17814. /**
  17815. * Get all direct children of this node
  17816. * @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
  17817. * @returns an array of {BABYLON.Node}
  17818. */
  17819. Node.prototype.getChildren = function (predicate) {
  17820. return this.getDescendants(true, predicate);
  17821. };
  17822. /** @hidden */
  17823. Node.prototype._setReady = function (state) {
  17824. if (state === this._isReady) {
  17825. return;
  17826. }
  17827. if (!state) {
  17828. this._isReady = false;
  17829. return;
  17830. }
  17831. if (this.onReady) {
  17832. this.onReady(this);
  17833. }
  17834. this._isReady = true;
  17835. };
  17836. /**
  17837. * Get an animation by name
  17838. * @param name defines the name of the animation to look for
  17839. * @returns null if not found else the requested animation
  17840. */
  17841. Node.prototype.getAnimationByName = function (name) {
  17842. for (var i = 0; i < this.animations.length; i++) {
  17843. var animation = this.animations[i];
  17844. if (animation.name === name) {
  17845. return animation;
  17846. }
  17847. }
  17848. return null;
  17849. };
  17850. /**
  17851. * Creates an animation range for this node
  17852. * @param name defines the name of the range
  17853. * @param from defines the starting key
  17854. * @param to defines the end key
  17855. */
  17856. Node.prototype.createAnimationRange = function (name, from, to) {
  17857. // check name not already in use
  17858. if (!this._ranges[name]) {
  17859. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17860. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17861. if (this.animations[i]) {
  17862. this.animations[i].createRange(name, from, to);
  17863. }
  17864. }
  17865. }
  17866. };
  17867. /**
  17868. * Delete a specific animation range
  17869. * @param name defines the name of the range to delete
  17870. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17871. */
  17872. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17873. if (deleteFrames === void 0) { deleteFrames = true; }
  17874. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17875. if (this.animations[i]) {
  17876. this.animations[i].deleteRange(name, deleteFrames);
  17877. }
  17878. }
  17879. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17880. };
  17881. /**
  17882. * Get an animation range by name
  17883. * @param name defines the name of the animation range to look for
  17884. * @returns null if not found else the requested animation range
  17885. */
  17886. Node.prototype.getAnimationRange = function (name) {
  17887. return this._ranges[name];
  17888. };
  17889. /**
  17890. * Will start the animation sequence
  17891. * @param name defines the range frames for animation sequence
  17892. * @param loop defines if the animation should loop (false by default)
  17893. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17894. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17895. * @returns the object created for this animation. If range does not exist, it will return null
  17896. */
  17897. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17898. var range = this.getAnimationRange(name);
  17899. if (!range) {
  17900. return null;
  17901. }
  17902. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17903. };
  17904. /**
  17905. * Serialize animation ranges into a JSON compatible object
  17906. * @returns serialization object
  17907. */
  17908. Node.prototype.serializeAnimationRanges = function () {
  17909. var serializationRanges = [];
  17910. for (var name in this._ranges) {
  17911. var localRange = this._ranges[name];
  17912. if (!localRange) {
  17913. continue;
  17914. }
  17915. var range = {};
  17916. range.name = name;
  17917. range.from = localRange.from;
  17918. range.to = localRange.to;
  17919. serializationRanges.push(range);
  17920. }
  17921. return serializationRanges;
  17922. };
  17923. /**
  17924. * Computes the world matrix of the node
  17925. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17926. * @returns the world matrix
  17927. */
  17928. Node.prototype.computeWorldMatrix = function (force) {
  17929. return BABYLON.Matrix.Identity();
  17930. };
  17931. /**
  17932. * Releases resources associated with this node.
  17933. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17934. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17935. */
  17936. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17937. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17938. if (!doNotRecurse) {
  17939. var nodes = this.getDescendants(true);
  17940. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17941. var node = nodes_1[_i];
  17942. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17943. }
  17944. }
  17945. else {
  17946. var transformNodes = this.getChildTransformNodes(true);
  17947. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17948. var transformNode = transformNodes_1[_a];
  17949. transformNode.parent = null;
  17950. transformNode.computeWorldMatrix(true);
  17951. }
  17952. }
  17953. this.parent = null;
  17954. // Callback
  17955. this.onDisposeObservable.notifyObservers(this);
  17956. this.onDisposeObservable.clear();
  17957. // Behaviors
  17958. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17959. var behavior = _c[_b];
  17960. behavior.detach();
  17961. }
  17962. this._behaviors = [];
  17963. this._isDisposed = true;
  17964. };
  17965. /**
  17966. * Parse animation range data from a serialization object and store them into a given node
  17967. * @param node defines where to store the animation ranges
  17968. * @param parsedNode defines the serialization object to read data from
  17969. * @param scene defines the hosting scene
  17970. */
  17971. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17972. if (parsedNode.ranges) {
  17973. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17974. var data = parsedNode.ranges[index];
  17975. node.createAnimationRange(data.name, data.from, data.to);
  17976. }
  17977. }
  17978. };
  17979. __decorate([
  17980. BABYLON.serialize()
  17981. ], Node.prototype, "name", void 0);
  17982. __decorate([
  17983. BABYLON.serialize()
  17984. ], Node.prototype, "id", void 0);
  17985. __decorate([
  17986. BABYLON.serialize()
  17987. ], Node.prototype, "uniqueId", void 0);
  17988. __decorate([
  17989. BABYLON.serialize()
  17990. ], Node.prototype, "state", void 0);
  17991. __decorate([
  17992. BABYLON.serialize()
  17993. ], Node.prototype, "metadata", void 0);
  17994. return Node;
  17995. }());
  17996. BABYLON.Node = Node;
  17997. })(BABYLON || (BABYLON = {}));
  17998. //# sourceMappingURL=babylon.node.js.map
  17999. var BABYLON;
  18000. (function (BABYLON) {
  18001. var BoundingSphere = /** @class */ (function () {
  18002. /**
  18003. * Creates a new bounding sphere
  18004. * @param min defines the minimum vector (in local space)
  18005. * @param max defines the maximum vector (in local space)
  18006. */
  18007. function BoundingSphere(min, max) {
  18008. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18009. this.reConstruct(min, max);
  18010. }
  18011. /**
  18012. * Recreates the entire bounding sphere from scratch
  18013. * @param min defines the new minimum vector (in local space)
  18014. * @param max defines the new maximum vector (in local space)
  18015. */
  18016. BoundingSphere.prototype.reConstruct = function (min, max) {
  18017. this.minimum = min.clone();
  18018. this.maximum = max.clone();
  18019. var distance = BABYLON.Vector3.Distance(min, max);
  18020. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18021. this.radius = distance * 0.5;
  18022. this.centerWorld = BABYLON.Vector3.Zero();
  18023. this._update(BABYLON.Matrix.Identity());
  18024. };
  18025. // Methods
  18026. BoundingSphere.prototype._update = function (world) {
  18027. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18028. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18029. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18030. };
  18031. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18032. for (var i = 0; i < 6; i++) {
  18033. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18034. return false;
  18035. }
  18036. return true;
  18037. };
  18038. BoundingSphere.prototype.intersectsPoint = function (point) {
  18039. var x = this.centerWorld.x - point.x;
  18040. var y = this.centerWorld.y - point.y;
  18041. var z = this.centerWorld.z - point.z;
  18042. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18043. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18044. return false;
  18045. return true;
  18046. };
  18047. // Statics
  18048. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18049. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18050. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18051. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18052. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18053. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18054. return false;
  18055. return true;
  18056. };
  18057. return BoundingSphere;
  18058. }());
  18059. BABYLON.BoundingSphere = BoundingSphere;
  18060. })(BABYLON || (BABYLON = {}));
  18061. //# sourceMappingURL=babylon.boundingSphere.js.map
  18062. var BABYLON;
  18063. (function (BABYLON) {
  18064. var BoundingBox = /** @class */ (function () {
  18065. /**
  18066. * Creates a new bounding box
  18067. * @param min defines the minimum vector (in local space)
  18068. * @param max defines the maximum vector (in local space)
  18069. */
  18070. function BoundingBox(min, max) {
  18071. this.vectorsWorld = new Array();
  18072. this.reConstruct(min, max);
  18073. }
  18074. // Methods
  18075. /**
  18076. * Recreates the entire bounding box from scratch
  18077. * @param min defines the new minimum vector (in local space)
  18078. * @param max defines the new maximum vector (in local space)
  18079. */
  18080. BoundingBox.prototype.reConstruct = function (min, max) {
  18081. this.minimum = min.clone();
  18082. this.maximum = max.clone();
  18083. // Bounding vectors
  18084. this.vectors = new Array();
  18085. this.vectors.push(this.minimum.clone());
  18086. this.vectors.push(this.maximum.clone());
  18087. this.vectors.push(this.minimum.clone());
  18088. this.vectors[2].x = this.maximum.x;
  18089. this.vectors.push(this.minimum.clone());
  18090. this.vectors[3].y = this.maximum.y;
  18091. this.vectors.push(this.minimum.clone());
  18092. this.vectors[4].z = this.maximum.z;
  18093. this.vectors.push(this.maximum.clone());
  18094. this.vectors[5].z = this.minimum.z;
  18095. this.vectors.push(this.maximum.clone());
  18096. this.vectors[6].x = this.minimum.x;
  18097. this.vectors.push(this.maximum.clone());
  18098. this.vectors[7].y = this.minimum.y;
  18099. // OBB
  18100. this.center = this.maximum.add(this.minimum).scale(0.5);
  18101. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18102. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18103. // World
  18104. for (var index = 0; index < this.vectors.length; index++) {
  18105. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18106. }
  18107. this.minimumWorld = BABYLON.Vector3.Zero();
  18108. this.maximumWorld = BABYLON.Vector3.Zero();
  18109. this.centerWorld = BABYLON.Vector3.Zero();
  18110. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18111. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18112. };
  18113. BoundingBox.prototype.getWorldMatrix = function () {
  18114. return this._worldMatrix;
  18115. };
  18116. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18117. this._worldMatrix.copyFrom(matrix);
  18118. return this;
  18119. };
  18120. BoundingBox.prototype._update = function (world) {
  18121. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18122. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18123. for (var index = 0; index < this.vectors.length; index++) {
  18124. var v = this.vectorsWorld[index];
  18125. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18126. if (v.x < this.minimumWorld.x)
  18127. this.minimumWorld.x = v.x;
  18128. if (v.y < this.minimumWorld.y)
  18129. this.minimumWorld.y = v.y;
  18130. if (v.z < this.minimumWorld.z)
  18131. this.minimumWorld.z = v.z;
  18132. if (v.x > this.maximumWorld.x)
  18133. this.maximumWorld.x = v.x;
  18134. if (v.y > this.maximumWorld.y)
  18135. this.maximumWorld.y = v.y;
  18136. if (v.z > this.maximumWorld.z)
  18137. this.maximumWorld.z = v.z;
  18138. }
  18139. // Extend
  18140. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18141. this.extendSizeWorld.scaleInPlace(0.5);
  18142. // OBB
  18143. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18144. this.centerWorld.scaleInPlace(0.5);
  18145. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18146. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18147. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18148. this._worldMatrix = world;
  18149. };
  18150. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18151. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18152. };
  18153. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18154. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18155. };
  18156. BoundingBox.prototype.intersectsPoint = function (point) {
  18157. var delta = -BABYLON.Epsilon;
  18158. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18159. return false;
  18160. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18161. return false;
  18162. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18163. return false;
  18164. return true;
  18165. };
  18166. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18167. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18168. };
  18169. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18170. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18171. return false;
  18172. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18173. return false;
  18174. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18175. return false;
  18176. return true;
  18177. };
  18178. // Statics
  18179. BoundingBox.Intersects = function (box0, box1) {
  18180. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18181. return false;
  18182. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18183. return false;
  18184. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18185. return false;
  18186. return true;
  18187. };
  18188. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18189. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18190. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18191. return (num <= (sphereRadius * sphereRadius));
  18192. };
  18193. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18194. for (var p = 0; p < 6; p++) {
  18195. for (var i = 0; i < 8; i++) {
  18196. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18197. return false;
  18198. }
  18199. }
  18200. }
  18201. return true;
  18202. };
  18203. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18204. for (var p = 0; p < 6; p++) {
  18205. var inCount = 8;
  18206. for (var i = 0; i < 8; i++) {
  18207. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18208. --inCount;
  18209. }
  18210. else {
  18211. break;
  18212. }
  18213. }
  18214. if (inCount === 0)
  18215. return false;
  18216. }
  18217. return true;
  18218. };
  18219. return BoundingBox;
  18220. }());
  18221. BABYLON.BoundingBox = BoundingBox;
  18222. })(BABYLON || (BABYLON = {}));
  18223. //# sourceMappingURL=babylon.boundingBox.js.map
  18224. var BABYLON;
  18225. (function (BABYLON) {
  18226. var computeBoxExtents = function (axis, box) {
  18227. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18228. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18229. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18230. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18231. var r = r0 + r1 + r2;
  18232. return {
  18233. min: p - r,
  18234. max: p + r
  18235. };
  18236. };
  18237. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18238. var axisOverlap = function (axis, box0, box1) {
  18239. var result0 = computeBoxExtents(axis, box0);
  18240. var result1 = computeBoxExtents(axis, box1);
  18241. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18242. };
  18243. var BoundingInfo = /** @class */ (function () {
  18244. function BoundingInfo(minimum, maximum) {
  18245. this.minimum = minimum;
  18246. this.maximum = maximum;
  18247. this._isLocked = false;
  18248. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18249. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18250. }
  18251. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18252. get: function () {
  18253. return this._isLocked;
  18254. },
  18255. set: function (value) {
  18256. this._isLocked = value;
  18257. },
  18258. enumerable: true,
  18259. configurable: true
  18260. });
  18261. // Methods
  18262. BoundingInfo.prototype.update = function (world) {
  18263. if (this._isLocked) {
  18264. return;
  18265. }
  18266. this.boundingBox._update(world);
  18267. this.boundingSphere._update(world);
  18268. };
  18269. /**
  18270. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18271. * @param center New center of the bounding info
  18272. * @param extend New extend of the bounding info
  18273. */
  18274. BoundingInfo.prototype.centerOn = function (center, extend) {
  18275. this.minimum = center.subtract(extend);
  18276. this.maximum = center.add(extend);
  18277. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18278. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18279. return this;
  18280. };
  18281. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18282. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18283. return false;
  18284. return this.boundingBox.isInFrustum(frustumPlanes);
  18285. };
  18286. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18287. /**
  18288. * Gets the world distance between the min and max points of the bounding box
  18289. */
  18290. get: function () {
  18291. var boundingBox = this.boundingBox;
  18292. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18293. return size.length();
  18294. },
  18295. enumerable: true,
  18296. configurable: true
  18297. });
  18298. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18299. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18300. };
  18301. BoundingInfo.prototype._checkCollision = function (collider) {
  18302. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18303. };
  18304. BoundingInfo.prototype.intersectsPoint = function (point) {
  18305. if (!this.boundingSphere.centerWorld) {
  18306. return false;
  18307. }
  18308. if (!this.boundingSphere.intersectsPoint(point)) {
  18309. return false;
  18310. }
  18311. if (!this.boundingBox.intersectsPoint(point)) {
  18312. return false;
  18313. }
  18314. return true;
  18315. };
  18316. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18317. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18318. return false;
  18319. }
  18320. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18321. return false;
  18322. }
  18323. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18324. return false;
  18325. }
  18326. if (!precise) {
  18327. return true;
  18328. }
  18329. var box0 = this.boundingBox;
  18330. var box1 = boundingInfo.boundingBox;
  18331. if (!axisOverlap(box0.directions[0], box0, box1))
  18332. return false;
  18333. if (!axisOverlap(box0.directions[1], box0, box1))
  18334. return false;
  18335. if (!axisOverlap(box0.directions[2], box0, box1))
  18336. return false;
  18337. if (!axisOverlap(box1.directions[0], box0, box1))
  18338. return false;
  18339. if (!axisOverlap(box1.directions[1], box0, box1))
  18340. return false;
  18341. if (!axisOverlap(box1.directions[2], box0, box1))
  18342. return false;
  18343. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18344. return false;
  18345. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18346. return false;
  18347. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18348. return false;
  18349. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18350. return false;
  18351. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18352. return false;
  18353. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18354. return false;
  18355. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18356. return false;
  18357. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18358. return false;
  18359. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18360. return false;
  18361. return true;
  18362. };
  18363. return BoundingInfo;
  18364. }());
  18365. BABYLON.BoundingInfo = BoundingInfo;
  18366. })(BABYLON || (BABYLON = {}));
  18367. //# sourceMappingURL=babylon.boundingInfo.js.map
  18368. var BABYLON;
  18369. (function (BABYLON) {
  18370. var TransformNode = /** @class */ (function (_super) {
  18371. __extends(TransformNode, _super);
  18372. function TransformNode(name, scene, isPure) {
  18373. if (scene === void 0) { scene = null; }
  18374. if (isPure === void 0) { isPure = true; }
  18375. var _this = _super.call(this, name, scene) || this;
  18376. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18377. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18378. _this._up = new BABYLON.Vector3(0, 1, 0);
  18379. _this._right = new BABYLON.Vector3(1, 0, 0);
  18380. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18381. // Properties
  18382. _this._rotation = BABYLON.Vector3.Zero();
  18383. _this._scaling = BABYLON.Vector3.One();
  18384. _this._isDirty = false;
  18385. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18386. _this.scalingDeterminant = 1;
  18387. _this.infiniteDistance = false;
  18388. _this.position = BABYLON.Vector3.Zero();
  18389. _this._localWorld = BABYLON.Matrix.Zero();
  18390. _this._worldMatrix = BABYLON.Matrix.Zero();
  18391. _this._worldMatrixDeterminant = 0;
  18392. _this._absolutePosition = BABYLON.Vector3.Zero();
  18393. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18394. _this._postMultiplyPivotMatrix = false;
  18395. _this._isWorldMatrixFrozen = false;
  18396. /**
  18397. * An event triggered after the world matrix is updated
  18398. */
  18399. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18400. _this._nonUniformScaling = false;
  18401. if (isPure) {
  18402. _this.getScene().addTransformNode(_this);
  18403. }
  18404. return _this;
  18405. }
  18406. /**
  18407. * Gets a string idenfifying the name of the class
  18408. * @returns "TransformNode" string
  18409. */
  18410. TransformNode.prototype.getClassName = function () {
  18411. return "TransformNode";
  18412. };
  18413. Object.defineProperty(TransformNode.prototype, "rotation", {
  18414. /**
  18415. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18416. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18417. * Default : (0.0, 0.0, 0.0)
  18418. */
  18419. get: function () {
  18420. return this._rotation;
  18421. },
  18422. set: function (newRotation) {
  18423. this._rotation = newRotation;
  18424. },
  18425. enumerable: true,
  18426. configurable: true
  18427. });
  18428. Object.defineProperty(TransformNode.prototype, "scaling", {
  18429. /**
  18430. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18431. * Default : (1.0, 1.0, 1.0)
  18432. */
  18433. get: function () {
  18434. return this._scaling;
  18435. },
  18436. /**
  18437. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18438. * Default : (1.0, 1.0, 1.0)
  18439. */
  18440. set: function (newScaling) {
  18441. this._scaling = newScaling;
  18442. },
  18443. enumerable: true,
  18444. configurable: true
  18445. });
  18446. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18447. /**
  18448. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18449. * It's null by default.
  18450. * 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)
  18451. */
  18452. get: function () {
  18453. return this._rotationQuaternion;
  18454. },
  18455. set: function (quaternion) {
  18456. this._rotationQuaternion = quaternion;
  18457. //reset the rotation vector.
  18458. if (quaternion && this.rotation.length()) {
  18459. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18460. }
  18461. },
  18462. enumerable: true,
  18463. configurable: true
  18464. });
  18465. Object.defineProperty(TransformNode.prototype, "forward", {
  18466. /**
  18467. * The forward direction of that transform in world space.
  18468. */
  18469. get: function () {
  18470. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18471. },
  18472. enumerable: true,
  18473. configurable: true
  18474. });
  18475. Object.defineProperty(TransformNode.prototype, "up", {
  18476. /**
  18477. * The up direction of that transform in world space.
  18478. */
  18479. get: function () {
  18480. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18481. },
  18482. enumerable: true,
  18483. configurable: true
  18484. });
  18485. Object.defineProperty(TransformNode.prototype, "right", {
  18486. /**
  18487. * The right direction of that transform in world space.
  18488. */
  18489. get: function () {
  18490. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18491. },
  18492. enumerable: true,
  18493. configurable: true
  18494. });
  18495. /**
  18496. * Returns the latest update of the World matrix
  18497. * Returns a Matrix.
  18498. */
  18499. TransformNode.prototype.getWorldMatrix = function () {
  18500. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18501. this.computeWorldMatrix();
  18502. }
  18503. return this._worldMatrix;
  18504. };
  18505. /** @hidden */
  18506. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18507. return this._worldMatrixDeterminant;
  18508. };
  18509. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18510. /**
  18511. * Returns directly the latest state of the mesh World matrix.
  18512. * A Matrix is returned.
  18513. */
  18514. get: function () {
  18515. return this._worldMatrix;
  18516. },
  18517. enumerable: true,
  18518. configurable: true
  18519. });
  18520. /**
  18521. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18522. * Returns the TransformNode.
  18523. */
  18524. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18525. this._poseMatrix.copyFrom(matrix);
  18526. return this;
  18527. };
  18528. /**
  18529. * Returns the mesh Pose matrix.
  18530. * Returned object : Matrix
  18531. */
  18532. TransformNode.prototype.getPoseMatrix = function () {
  18533. return this._poseMatrix;
  18534. };
  18535. TransformNode.prototype._isSynchronized = function () {
  18536. if (this._isDirty) {
  18537. return false;
  18538. }
  18539. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18540. return false;
  18541. if (this._cache.pivotMatrixUpdated) {
  18542. return false;
  18543. }
  18544. if (this.infiniteDistance) {
  18545. return false;
  18546. }
  18547. if (!this._cache.position.equals(this.position))
  18548. return false;
  18549. if (this.rotationQuaternion) {
  18550. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18551. return false;
  18552. }
  18553. if (!this._cache.rotation.equals(this.rotation))
  18554. return false;
  18555. if (!this._cache.scaling.equals(this.scaling))
  18556. return false;
  18557. return true;
  18558. };
  18559. TransformNode.prototype._initCache = function () {
  18560. _super.prototype._initCache.call(this);
  18561. this._cache.localMatrixUpdated = false;
  18562. this._cache.position = BABYLON.Vector3.Zero();
  18563. this._cache.scaling = BABYLON.Vector3.Zero();
  18564. this._cache.rotation = BABYLON.Vector3.Zero();
  18565. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18566. this._cache.billboardMode = -1;
  18567. };
  18568. TransformNode.prototype.markAsDirty = function (property) {
  18569. if (property === "rotation") {
  18570. this.rotationQuaternion = null;
  18571. }
  18572. this._currentRenderId = Number.MAX_VALUE;
  18573. this._isDirty = true;
  18574. return this;
  18575. };
  18576. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18577. /**
  18578. * Returns the current mesh absolute position.
  18579. * Retuns a Vector3.
  18580. */
  18581. get: function () {
  18582. return this._absolutePosition;
  18583. },
  18584. enumerable: true,
  18585. configurable: true
  18586. });
  18587. /**
  18588. * Sets a new matrix to apply before all other transformation
  18589. * @param matrix defines the transform matrix
  18590. * @returns the current TransformNode
  18591. */
  18592. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18593. return this.setPivotMatrix(matrix, false);
  18594. };
  18595. /**
  18596. * Sets a new pivot matrix to the current node
  18597. * @param matrix defines the new pivot matrix to use
  18598. * @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
  18599. * @returns the current TransformNode
  18600. */
  18601. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18602. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18603. this._pivotMatrix = matrix.clone();
  18604. this._cache.pivotMatrixUpdated = true;
  18605. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18606. if (this._postMultiplyPivotMatrix) {
  18607. if (!this._pivotMatrixInverse) {
  18608. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18609. }
  18610. else {
  18611. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18612. }
  18613. }
  18614. return this;
  18615. };
  18616. /**
  18617. * Returns the mesh pivot matrix.
  18618. * Default : Identity.
  18619. * A Matrix is returned.
  18620. */
  18621. TransformNode.prototype.getPivotMatrix = function () {
  18622. return this._pivotMatrix;
  18623. };
  18624. /**
  18625. * Prevents the World matrix to be computed any longer.
  18626. * Returns the TransformNode.
  18627. */
  18628. TransformNode.prototype.freezeWorldMatrix = function () {
  18629. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18630. this.computeWorldMatrix(true);
  18631. this._isWorldMatrixFrozen = true;
  18632. return this;
  18633. };
  18634. /**
  18635. * Allows back the World matrix computation.
  18636. * Returns the TransformNode.
  18637. */
  18638. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18639. this._isWorldMatrixFrozen = false;
  18640. this.computeWorldMatrix(true);
  18641. return this;
  18642. };
  18643. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18644. /**
  18645. * True if the World matrix has been frozen.
  18646. * Returns a boolean.
  18647. */
  18648. get: function () {
  18649. return this._isWorldMatrixFrozen;
  18650. },
  18651. enumerable: true,
  18652. configurable: true
  18653. });
  18654. /**
  18655. * Retuns the mesh absolute position in the World.
  18656. * Returns a Vector3.
  18657. */
  18658. TransformNode.prototype.getAbsolutePosition = function () {
  18659. this.computeWorldMatrix();
  18660. return this._absolutePosition;
  18661. };
  18662. /**
  18663. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18664. * Returns the TransformNode.
  18665. */
  18666. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18667. if (!absolutePosition) {
  18668. return this;
  18669. }
  18670. var absolutePositionX;
  18671. var absolutePositionY;
  18672. var absolutePositionZ;
  18673. if (absolutePosition.x === undefined) {
  18674. if (arguments.length < 3) {
  18675. return this;
  18676. }
  18677. absolutePositionX = arguments[0];
  18678. absolutePositionY = arguments[1];
  18679. absolutePositionZ = arguments[2];
  18680. }
  18681. else {
  18682. absolutePositionX = absolutePosition.x;
  18683. absolutePositionY = absolutePosition.y;
  18684. absolutePositionZ = absolutePosition.z;
  18685. }
  18686. if (this.parent) {
  18687. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18688. invertParentWorldMatrix.invert();
  18689. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18690. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18691. }
  18692. else {
  18693. this.position.x = absolutePositionX;
  18694. this.position.y = absolutePositionY;
  18695. this.position.z = absolutePositionZ;
  18696. }
  18697. return this;
  18698. };
  18699. /**
  18700. * Sets the mesh position in its local space.
  18701. * Returns the TransformNode.
  18702. */
  18703. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18704. this.computeWorldMatrix();
  18705. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18706. return this;
  18707. };
  18708. /**
  18709. * Returns the mesh position in the local space from the current World matrix values.
  18710. * Returns a new Vector3.
  18711. */
  18712. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18713. this.computeWorldMatrix();
  18714. var invLocalWorldMatrix = this._localWorld.clone();
  18715. invLocalWorldMatrix.invert();
  18716. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18717. };
  18718. /**
  18719. * Translates the mesh along the passed Vector3 in its local space.
  18720. * Returns the TransformNode.
  18721. */
  18722. TransformNode.prototype.locallyTranslate = function (vector3) {
  18723. this.computeWorldMatrix(true);
  18724. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18725. return this;
  18726. };
  18727. /**
  18728. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18729. * @param targetPoint the position (must be in same space as current mesh) to look at
  18730. * @param yawCor optional yaw (y-axis) correction in radians
  18731. * @param pitchCor optional pitch (x-axis) correction in radians
  18732. * @param rollCor optional roll (z-axis) correction in radians
  18733. * @param space the choosen space of the target
  18734. * @returns the TransformNode.
  18735. */
  18736. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18737. if (yawCor === void 0) { yawCor = 0; }
  18738. if (pitchCor === void 0) { pitchCor = 0; }
  18739. if (rollCor === void 0) { rollCor = 0; }
  18740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18741. var dv = TransformNode._lookAtVectorCache;
  18742. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18743. targetPoint.subtractToRef(pos, dv);
  18744. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18745. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18746. var pitch = Math.atan2(dv.y, len);
  18747. if (this.rotationQuaternion) {
  18748. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18749. }
  18750. else {
  18751. this.rotation.x = pitch + pitchCor;
  18752. this.rotation.y = yaw + yawCor;
  18753. this.rotation.z = rollCor;
  18754. }
  18755. return this;
  18756. };
  18757. /**
  18758. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18759. * This Vector3 is expressed in the World space.
  18760. */
  18761. TransformNode.prototype.getDirection = function (localAxis) {
  18762. var result = BABYLON.Vector3.Zero();
  18763. this.getDirectionToRef(localAxis, result);
  18764. return result;
  18765. };
  18766. /**
  18767. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18768. * localAxis is expressed in the mesh local space.
  18769. * result is computed in the Wordl space from the mesh World matrix.
  18770. * Returns the TransformNode.
  18771. */
  18772. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18773. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18774. return this;
  18775. };
  18776. /**
  18777. * Sets a new pivot point to the current node
  18778. * @param point defines the new pivot point to use
  18779. * @param space defines if the point is in world or local space (local by default)
  18780. * @returns the current TransformNode
  18781. */
  18782. TransformNode.prototype.setPivotPoint = function (point, space) {
  18783. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18784. if (this.getScene().getRenderId() == 0) {
  18785. this.computeWorldMatrix(true);
  18786. }
  18787. var wm = this.getWorldMatrix();
  18788. if (space == BABYLON.Space.WORLD) {
  18789. var tmat = BABYLON.Tmp.Matrix[0];
  18790. wm.invertToRef(tmat);
  18791. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18792. }
  18793. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18794. };
  18795. /**
  18796. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18797. */
  18798. TransformNode.prototype.getPivotPoint = function () {
  18799. var point = BABYLON.Vector3.Zero();
  18800. this.getPivotPointToRef(point);
  18801. return point;
  18802. };
  18803. /**
  18804. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18805. * Returns the TransformNode.
  18806. */
  18807. TransformNode.prototype.getPivotPointToRef = function (result) {
  18808. result.x = -this._pivotMatrix.m[12];
  18809. result.y = -this._pivotMatrix.m[13];
  18810. result.z = -this._pivotMatrix.m[14];
  18811. return this;
  18812. };
  18813. /**
  18814. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18815. */
  18816. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18817. var point = BABYLON.Vector3.Zero();
  18818. this.getAbsolutePivotPointToRef(point);
  18819. return point;
  18820. };
  18821. /**
  18822. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18823. * Returns the TransformNode.
  18824. */
  18825. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18826. result.x = this._pivotMatrix.m[12];
  18827. result.y = this._pivotMatrix.m[13];
  18828. result.z = this._pivotMatrix.m[14];
  18829. this.getPivotPointToRef(result);
  18830. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18831. return this;
  18832. };
  18833. /**
  18834. * Defines the passed node as the parent of the current node.
  18835. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18836. * Returns the TransformNode.
  18837. */
  18838. TransformNode.prototype.setParent = function (node) {
  18839. if (node === null) {
  18840. var rotation = BABYLON.Tmp.Quaternion[0];
  18841. var position = BABYLON.Tmp.Vector3[0];
  18842. var scale = BABYLON.Tmp.Vector3[1];
  18843. if (this.parent && this.parent.computeWorldMatrix) {
  18844. this.parent.computeWorldMatrix(true);
  18845. }
  18846. this.computeWorldMatrix(true);
  18847. this.getWorldMatrix().decompose(scale, rotation, position);
  18848. if (this.rotationQuaternion) {
  18849. this.rotationQuaternion.copyFrom(rotation);
  18850. }
  18851. else {
  18852. rotation.toEulerAnglesToRef(this.rotation);
  18853. }
  18854. this.scaling.x = scale.x;
  18855. this.scaling.y = scale.y;
  18856. this.scaling.z = scale.z;
  18857. this.position.x = position.x;
  18858. this.position.y = position.y;
  18859. this.position.z = position.z;
  18860. }
  18861. else {
  18862. var rotation = BABYLON.Tmp.Quaternion[0];
  18863. var position = BABYLON.Tmp.Vector3[0];
  18864. var scale = BABYLON.Tmp.Vector3[1];
  18865. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18866. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18867. this.computeWorldMatrix(true);
  18868. node.computeWorldMatrix(true);
  18869. node.getWorldMatrix().invertToRef(invParentMatrix);
  18870. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18871. diffMatrix.decompose(scale, rotation, position);
  18872. if (this.rotationQuaternion) {
  18873. this.rotationQuaternion.copyFrom(rotation);
  18874. }
  18875. else {
  18876. rotation.toEulerAnglesToRef(this.rotation);
  18877. }
  18878. this.position.x = position.x;
  18879. this.position.y = position.y;
  18880. this.position.z = position.z;
  18881. this.scaling.x = scale.x;
  18882. this.scaling.y = scale.y;
  18883. this.scaling.z = scale.z;
  18884. }
  18885. this.parent = node;
  18886. return this;
  18887. };
  18888. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18889. get: function () {
  18890. return this._nonUniformScaling;
  18891. },
  18892. enumerable: true,
  18893. configurable: true
  18894. });
  18895. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18896. if (this._nonUniformScaling === value) {
  18897. return false;
  18898. }
  18899. this._nonUniformScaling = true;
  18900. return true;
  18901. };
  18902. /**
  18903. * Attach the current TransformNode to another TransformNode associated with a bone
  18904. * @param bone Bone affecting the TransformNode
  18905. * @param affectedTransformNode TransformNode associated with the bone
  18906. */
  18907. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18908. this._transformToBoneReferal = affectedTransformNode;
  18909. this.parent = bone;
  18910. if (bone.getWorldMatrix().determinant() < 0) {
  18911. this.scalingDeterminant *= -1;
  18912. }
  18913. return this;
  18914. };
  18915. TransformNode.prototype.detachFromBone = function () {
  18916. if (!this.parent) {
  18917. return this;
  18918. }
  18919. if (this.parent.getWorldMatrix().determinant() < 0) {
  18920. this.scalingDeterminant *= -1;
  18921. }
  18922. this._transformToBoneReferal = null;
  18923. this.parent = null;
  18924. return this;
  18925. };
  18926. /**
  18927. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18928. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18929. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18930. * The passed axis is also normalized.
  18931. * Returns the TransformNode.
  18932. */
  18933. TransformNode.prototype.rotate = function (axis, amount, space) {
  18934. axis.normalize();
  18935. if (!this.rotationQuaternion) {
  18936. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18937. this.rotation = BABYLON.Vector3.Zero();
  18938. }
  18939. var rotationQuaternion;
  18940. if (!space || space === BABYLON.Space.LOCAL) {
  18941. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18942. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18943. }
  18944. else {
  18945. if (this.parent) {
  18946. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18947. invertParentWorldMatrix.invert();
  18948. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18949. }
  18950. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18951. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18952. }
  18953. return this;
  18954. };
  18955. /**
  18956. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18957. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18958. * The passed axis is also normalized.
  18959. * Returns the TransformNode.
  18960. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18961. */
  18962. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18963. axis.normalize();
  18964. if (!this.rotationQuaternion) {
  18965. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18966. this.rotation.copyFromFloats(0, 0, 0);
  18967. }
  18968. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18969. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18970. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18971. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18972. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18973. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18974. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18975. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18976. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18977. return this;
  18978. };
  18979. /**
  18980. * Translates the mesh along the axis vector for the passed distance in the given space.
  18981. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18982. * Returns the TransformNode.
  18983. */
  18984. TransformNode.prototype.translate = function (axis, distance, space) {
  18985. var displacementVector = axis.scale(distance);
  18986. if (!space || space === BABYLON.Space.LOCAL) {
  18987. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18988. this.setPositionWithLocalVector(tempV3);
  18989. }
  18990. else {
  18991. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18992. }
  18993. return this;
  18994. };
  18995. /**
  18996. * Adds a rotation step to the mesh current rotation.
  18997. * x, y, z are Euler angles expressed in radians.
  18998. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18999. * This means this rotation is made in the mesh local space only.
  19000. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19001. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19002. * ```javascript
  19003. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19004. * ```
  19005. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19006. * 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.
  19007. * Returns the TransformNode.
  19008. */
  19009. TransformNode.prototype.addRotation = function (x, y, z) {
  19010. var rotationQuaternion;
  19011. if (this.rotationQuaternion) {
  19012. rotationQuaternion = this.rotationQuaternion;
  19013. }
  19014. else {
  19015. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19016. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19017. }
  19018. var accumulation = BABYLON.Tmp.Quaternion[0];
  19019. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19020. rotationQuaternion.multiplyInPlace(accumulation);
  19021. if (!this.rotationQuaternion) {
  19022. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19023. }
  19024. return this;
  19025. };
  19026. /**
  19027. * Computes the mesh World matrix and returns it.
  19028. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19029. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19030. * If the parameter `force`is set to `true`, the actual computation is done.
  19031. * Returns the mesh World Matrix.
  19032. */
  19033. TransformNode.prototype.computeWorldMatrix = function (force) {
  19034. if (this._isWorldMatrixFrozen) {
  19035. return this._worldMatrix;
  19036. }
  19037. if (!force && this.isSynchronized(true)) {
  19038. this._currentRenderId = this.getScene().getRenderId();
  19039. return this._worldMatrix;
  19040. }
  19041. this._cache.position.copyFrom(this.position);
  19042. this._cache.scaling.copyFrom(this.scaling);
  19043. this._cache.pivotMatrixUpdated = false;
  19044. this._cache.billboardMode = this.billboardMode;
  19045. this._currentRenderId = this.getScene().getRenderId();
  19046. this._childRenderId = this.getScene().getRenderId();
  19047. this._isDirty = false;
  19048. // Scaling
  19049. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19050. // Rotation
  19051. //rotate, if quaternion is set and rotation was used
  19052. if (this.rotationQuaternion) {
  19053. var len = this.rotation.length();
  19054. if (len) {
  19055. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19056. this.rotation.copyFromFloats(0, 0, 0);
  19057. }
  19058. }
  19059. if (this.rotationQuaternion) {
  19060. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19061. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19062. }
  19063. else {
  19064. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19065. this._cache.rotation.copyFrom(this.rotation);
  19066. }
  19067. // Translation
  19068. var camera = this.getScene().activeCamera;
  19069. if (this.infiniteDistance && !this.parent && camera) {
  19070. var cameraWorldMatrix = camera.getWorldMatrix();
  19071. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19072. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19073. }
  19074. else {
  19075. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19076. }
  19077. // Composing transformations
  19078. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19079. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19080. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19081. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19082. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19083. // Need to decompose each rotation here
  19084. var currentPosition = BABYLON.Tmp.Vector3[3];
  19085. if (this.parent && this.parent.getWorldMatrix) {
  19086. if (this._transformToBoneReferal) {
  19087. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19088. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19089. }
  19090. else {
  19091. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19092. }
  19093. }
  19094. else {
  19095. currentPosition.copyFrom(this.position);
  19096. }
  19097. currentPosition.subtractInPlace(camera.globalPosition);
  19098. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19099. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19100. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19101. }
  19102. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19103. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19104. }
  19105. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19106. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19107. }
  19108. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19109. }
  19110. else {
  19111. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19112. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19113. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19114. }
  19115. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19116. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19117. }
  19118. // Local world
  19119. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19120. // Parent
  19121. if (this.parent && this.parent.getWorldMatrix) {
  19122. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19123. if (this._transformToBoneReferal) {
  19124. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19125. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19126. }
  19127. else {
  19128. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19129. }
  19130. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19131. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19132. this._worldMatrix.copyFrom(this._localWorld);
  19133. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19134. }
  19135. else {
  19136. if (this._transformToBoneReferal) {
  19137. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19138. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19139. }
  19140. else {
  19141. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19142. }
  19143. }
  19144. this._markSyncedWithParent();
  19145. }
  19146. else {
  19147. this._worldMatrix.copyFrom(this._localWorld);
  19148. }
  19149. // Post multiply inverse of pivotMatrix
  19150. if (this._postMultiplyPivotMatrix) {
  19151. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19152. }
  19153. // Normal matrix
  19154. if (this.scaling.isNonUniform) {
  19155. this._updateNonUniformScalingState(true);
  19156. }
  19157. else if (this.parent && this.parent._nonUniformScaling) {
  19158. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19159. }
  19160. else {
  19161. this._updateNonUniformScalingState(false);
  19162. }
  19163. this._afterComputeWorldMatrix();
  19164. // Absolute position
  19165. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19166. // Callbacks
  19167. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19168. if (!this._poseMatrix) {
  19169. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19170. }
  19171. // Cache the determinant
  19172. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19173. return this._worldMatrix;
  19174. };
  19175. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19176. };
  19177. /**
  19178. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19179. * @param func: callback function to add
  19180. *
  19181. * Returns the TransformNode.
  19182. */
  19183. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19184. this.onAfterWorldMatrixUpdateObservable.add(func);
  19185. return this;
  19186. };
  19187. /**
  19188. * Removes a registered callback function.
  19189. * Returns the TransformNode.
  19190. */
  19191. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19192. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19193. return this;
  19194. };
  19195. /**
  19196. * Clone the current transform node
  19197. * Returns the new transform node
  19198. * @param name Name of the new clone
  19199. * @param newParent New parent for the clone
  19200. * @param doNotCloneChildren Do not clone children hierarchy
  19201. */
  19202. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19203. var _this = this;
  19204. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19205. result.name = name;
  19206. result.id = name;
  19207. if (newParent) {
  19208. result.parent = newParent;
  19209. }
  19210. if (!doNotCloneChildren) {
  19211. // Children
  19212. var directDescendants = this.getDescendants(true);
  19213. for (var index = 0; index < directDescendants.length; index++) {
  19214. var child = directDescendants[index];
  19215. if (child.clone) {
  19216. child.clone(name + "." + child.name, result);
  19217. }
  19218. }
  19219. }
  19220. return result;
  19221. };
  19222. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19223. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19224. serializationObject.type = this.getClassName();
  19225. // Parent
  19226. if (this.parent) {
  19227. serializationObject.parentId = this.parent.id;
  19228. }
  19229. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19230. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19231. }
  19232. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19233. serializationObject.isEnabled = this.isEnabled();
  19234. // Parent
  19235. if (this.parent) {
  19236. serializationObject.parentId = this.parent.id;
  19237. }
  19238. return serializationObject;
  19239. };
  19240. // Statics
  19241. /**
  19242. * Returns a new TransformNode object parsed from the source provided.
  19243. * The parameter `parsedMesh` is the source.
  19244. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19245. */
  19246. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19247. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19248. if (BABYLON.Tags) {
  19249. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19250. }
  19251. if (parsedTransformNode.localMatrix) {
  19252. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19253. }
  19254. else if (parsedTransformNode.pivotMatrix) {
  19255. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19256. }
  19257. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19258. // Parent
  19259. if (parsedTransformNode.parentId) {
  19260. transformNode._waitingParentId = parsedTransformNode.parentId;
  19261. }
  19262. return transformNode;
  19263. };
  19264. /**
  19265. * Releases resources associated with this transform node.
  19266. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19267. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19268. */
  19269. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19270. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19271. // Animations
  19272. this.getScene().stopAnimation(this);
  19273. // Remove from scene
  19274. this.getScene().removeTransformNode(this);
  19275. this.onAfterWorldMatrixUpdateObservable.clear();
  19276. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19277. };
  19278. // Statics
  19279. TransformNode.BILLBOARDMODE_NONE = 0;
  19280. TransformNode.BILLBOARDMODE_X = 1;
  19281. TransformNode.BILLBOARDMODE_Y = 2;
  19282. TransformNode.BILLBOARDMODE_Z = 4;
  19283. TransformNode.BILLBOARDMODE_ALL = 7;
  19284. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19285. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19286. __decorate([
  19287. BABYLON.serializeAsVector3()
  19288. ], TransformNode.prototype, "_rotation", void 0);
  19289. __decorate([
  19290. BABYLON.serializeAsQuaternion()
  19291. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19292. __decorate([
  19293. BABYLON.serializeAsVector3()
  19294. ], TransformNode.prototype, "_scaling", void 0);
  19295. __decorate([
  19296. BABYLON.serialize()
  19297. ], TransformNode.prototype, "billboardMode", void 0);
  19298. __decorate([
  19299. BABYLON.serialize()
  19300. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19301. __decorate([
  19302. BABYLON.serialize()
  19303. ], TransformNode.prototype, "infiniteDistance", void 0);
  19304. __decorate([
  19305. BABYLON.serializeAsVector3()
  19306. ], TransformNode.prototype, "position", void 0);
  19307. return TransformNode;
  19308. }(BABYLON.Node));
  19309. BABYLON.TransformNode = TransformNode;
  19310. })(BABYLON || (BABYLON = {}));
  19311. //# sourceMappingURL=babylon.transformNode.js.map
  19312. var BABYLON;
  19313. (function (BABYLON) {
  19314. /**
  19315. * Class used to store all common mesh properties
  19316. */
  19317. var AbstractMesh = /** @class */ (function (_super) {
  19318. __extends(AbstractMesh, _super);
  19319. // Constructor
  19320. /**
  19321. * Creates a new AbstractMesh
  19322. * @param name defines the name of the mesh
  19323. * @param scene defines the hosting scene
  19324. */
  19325. function AbstractMesh(name, scene) {
  19326. if (scene === void 0) { scene = null; }
  19327. var _this = _super.call(this, name, scene, false) || this;
  19328. _this._facetNb = 0; // facet number
  19329. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19330. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19331. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19332. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19333. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19334. _this._subDiv = {
  19335. max: 1,
  19336. X: 1,
  19337. Y: 1,
  19338. Z: 1
  19339. };
  19340. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19341. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19342. // Events
  19343. /**
  19344. * An event triggered when this mesh collides with another one
  19345. */
  19346. _this.onCollideObservable = new BABYLON.Observable();
  19347. /**
  19348. * An event triggered when the collision's position changes
  19349. */
  19350. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19351. /**
  19352. * An event triggered when material is changed
  19353. */
  19354. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19355. // Properties
  19356. /**
  19357. * Gets or sets the orientation for POV movement & rotation
  19358. */
  19359. _this.definedFacingForward = true;
  19360. /**
  19361. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19362. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19363. * * 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.
  19364. * @see http://doc.babylonjs.com/features/occlusionquery
  19365. */
  19366. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19367. /**
  19368. * 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:
  19369. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19370. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19371. * * 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.
  19372. * @see http://doc.babylonjs.com/features/occlusionquery
  19373. */
  19374. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19375. /**
  19376. * 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.
  19377. * The default value is -1 which means don't break the query and wait till the result
  19378. * @see http://doc.babylonjs.com/features/occlusionquery
  19379. */
  19380. _this.occlusionRetryCount = -1;
  19381. _this._occlusionInternalRetryCounter = 0;
  19382. _this._isOccluded = false;
  19383. _this._isOcclusionQueryInProgress = false;
  19384. _this._visibility = 1.0;
  19385. /** Gets or sets the alpha index used to sort transparent meshes
  19386. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19387. */
  19388. _this.alphaIndex = Number.MAX_VALUE;
  19389. /**
  19390. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19391. */
  19392. _this.isVisible = true;
  19393. /**
  19394. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19395. */
  19396. _this.isPickable = true;
  19397. /**
  19398. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19399. */
  19400. _this.showBoundingBox = false;
  19401. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19402. _this.showSubMeshesBoundingBox = false;
  19403. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19404. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19405. */
  19406. _this.isBlocker = false;
  19407. /**
  19408. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19409. */
  19410. _this.enablePointerMoveEvents = false;
  19411. /**
  19412. * Specifies the rendering group id for this mesh (0 by default)
  19413. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19414. */
  19415. _this.renderingGroupId = 0;
  19416. _this._receiveShadows = false;
  19417. /**
  19418. * Gets or sets a boolean indicating if the outline must be rendered as well
  19419. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19420. */
  19421. _this.renderOutline = false;
  19422. /** Defines color to use when rendering outline */
  19423. _this.outlineColor = BABYLON.Color3.Red();
  19424. /** Define width to use when rendering outline */
  19425. _this.outlineWidth = 0.02;
  19426. /**
  19427. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19428. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19429. */
  19430. _this.renderOverlay = false;
  19431. /** Defines color to use when rendering overlay */
  19432. _this.overlayColor = BABYLON.Color3.Red();
  19433. /** Defines alpha to use when rendering overlay */
  19434. _this.overlayAlpha = 0.5;
  19435. _this._hasVertexAlpha = false;
  19436. _this._useVertexColors = true;
  19437. _this._computeBonesUsingShaders = true;
  19438. _this._numBoneInfluencers = 4;
  19439. _this._applyFog = true;
  19440. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19441. _this.useOctreeForRenderingSelection = true;
  19442. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19443. _this.useOctreeForPicking = true;
  19444. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19445. _this.useOctreeForCollisions = true;
  19446. _this._layerMask = 0x0FFFFFFF;
  19447. /**
  19448. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19449. */
  19450. _this.alwaysSelectAsActiveMesh = false;
  19451. /**
  19452. * Gets or sets the current action manager
  19453. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19454. */
  19455. _this.actionManager = null;
  19456. /**
  19457. * Gets or sets impostor used for physic simulation
  19458. * @see http://doc.babylonjs.com/features/physics_engine
  19459. */
  19460. _this.physicsImpostor = null;
  19461. // Collisions
  19462. _this._checkCollisions = false;
  19463. _this._collisionMask = -1;
  19464. _this._collisionGroup = -1;
  19465. /**
  19466. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19467. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19468. */
  19469. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19470. /**
  19471. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19472. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19473. */
  19474. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19475. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19476. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19477. // Edges
  19478. /**
  19479. * Defines edge width used when edgesRenderer is enabled
  19480. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19481. */
  19482. _this.edgesWidth = 1;
  19483. /**
  19484. * Defines edge color used when edgesRenderer is enabled
  19485. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19486. */
  19487. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19488. // Cache
  19489. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19490. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19491. /** @hidden */
  19492. _this._renderId = 0;
  19493. /** @hidden */
  19494. _this._intersectionsInProgress = new Array();
  19495. /** @hidden */
  19496. _this._unIndexed = false;
  19497. /** @hidden */
  19498. _this._lightSources = new Array();
  19499. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19500. if (collidedMesh === void 0) { collidedMesh = null; }
  19501. //TODO move this to the collision coordinator!
  19502. if (_this.getScene().workerCollisions)
  19503. newPosition.multiplyInPlace(_this._collider._radius);
  19504. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19505. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19506. _this.position.addInPlace(_this._diffPositionForCollisions);
  19507. }
  19508. if (collidedMesh) {
  19509. _this.onCollideObservable.notifyObservers(collidedMesh);
  19510. }
  19511. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19512. };
  19513. _this.getScene().addMesh(_this);
  19514. _this._resyncLightSources();
  19515. return _this;
  19516. }
  19517. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19518. /**
  19519. * No billboard
  19520. */
  19521. get: function () {
  19522. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19528. /** Billboard on X axis */
  19529. get: function () {
  19530. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19531. },
  19532. enumerable: true,
  19533. configurable: true
  19534. });
  19535. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19536. /** Billboard on Y axis */
  19537. get: function () {
  19538. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19539. },
  19540. enumerable: true,
  19541. configurable: true
  19542. });
  19543. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19544. /** Billboard on Z axis */
  19545. get: function () {
  19546. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19547. },
  19548. enumerable: true,
  19549. configurable: true
  19550. });
  19551. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19552. /** Billboard on all axes */
  19553. get: function () {
  19554. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19560. /**
  19561. * Gets the number of facets in the mesh
  19562. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19563. */
  19564. get: function () {
  19565. return this._facetNb;
  19566. },
  19567. enumerable: true,
  19568. configurable: true
  19569. });
  19570. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19571. /**
  19572. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19573. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19574. */
  19575. get: function () {
  19576. return this._partitioningSubdivisions;
  19577. },
  19578. set: function (nb) {
  19579. this._partitioningSubdivisions = nb;
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19585. /**
  19586. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19587. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19588. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19589. */
  19590. get: function () {
  19591. return this._partitioningBBoxRatio;
  19592. },
  19593. set: function (ratio) {
  19594. this._partitioningBBoxRatio = ratio;
  19595. },
  19596. enumerable: true,
  19597. configurable: true
  19598. });
  19599. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19600. /**
  19601. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19602. * Works only for updatable meshes.
  19603. * Doesn't work with multi-materials
  19604. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19605. */
  19606. get: function () {
  19607. return this._facetDepthSort;
  19608. },
  19609. set: function (sort) {
  19610. this._facetDepthSort = sort;
  19611. },
  19612. enumerable: true,
  19613. configurable: true
  19614. });
  19615. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19616. /**
  19617. * The location (Vector3) where the facet depth sort must be computed from.
  19618. * By default, the active camera position.
  19619. * Used only when facet depth sort is enabled
  19620. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19621. */
  19622. get: function () {
  19623. return this._facetDepthSortFrom;
  19624. },
  19625. set: function (location) {
  19626. this._facetDepthSortFrom = location;
  19627. },
  19628. enumerable: true,
  19629. configurable: true
  19630. });
  19631. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19632. /**
  19633. * gets a boolean indicating if facetData is enabled
  19634. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19635. */
  19636. get: function () {
  19637. return this._facetDataEnabled;
  19638. },
  19639. enumerable: true,
  19640. configurable: true
  19641. });
  19642. /** @hidden */
  19643. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19644. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19645. return false;
  19646. }
  19647. this._markSubMeshesAsMiscDirty();
  19648. return true;
  19649. };
  19650. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19651. /** Set a function to call when this mesh collides with another one */
  19652. set: function (callback) {
  19653. if (this._onCollideObserver) {
  19654. this.onCollideObservable.remove(this._onCollideObserver);
  19655. }
  19656. this._onCollideObserver = this.onCollideObservable.add(callback);
  19657. },
  19658. enumerable: true,
  19659. configurable: true
  19660. });
  19661. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19662. /** Set a function to call when the collision's position changes */
  19663. set: function (callback) {
  19664. if (this._onCollisionPositionChangeObserver) {
  19665. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19666. }
  19667. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19668. },
  19669. enumerable: true,
  19670. configurable: true
  19671. });
  19672. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19673. /**
  19674. * 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
  19675. * @see http://doc.babylonjs.com/features/occlusionquery
  19676. */
  19677. get: function () {
  19678. return this._isOccluded;
  19679. },
  19680. set: function (value) {
  19681. this._isOccluded = value;
  19682. },
  19683. enumerable: true,
  19684. configurable: true
  19685. });
  19686. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19687. /**
  19688. * Flag to check the progress status of the query
  19689. * @see http://doc.babylonjs.com/features/occlusionquery
  19690. */
  19691. get: function () {
  19692. return this._isOcclusionQueryInProgress;
  19693. },
  19694. enumerable: true,
  19695. configurable: true
  19696. });
  19697. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19698. /**
  19699. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19700. */
  19701. get: function () {
  19702. return this._visibility;
  19703. },
  19704. /**
  19705. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19706. */
  19707. set: function (value) {
  19708. if (this._visibility === value) {
  19709. return;
  19710. }
  19711. this._visibility = value;
  19712. this._markSubMeshesAsMiscDirty();
  19713. },
  19714. enumerable: true,
  19715. configurable: true
  19716. });
  19717. Object.defineProperty(AbstractMesh.prototype, "material", {
  19718. /** Gets or sets current material */
  19719. get: function () {
  19720. return this._material;
  19721. },
  19722. set: function (value) {
  19723. if (this._material === value) {
  19724. return;
  19725. }
  19726. this._material = value;
  19727. if (this.onMaterialChangedObservable.hasObservers) {
  19728. this.onMaterialChangedObservable.notifyObservers(this);
  19729. }
  19730. if (!this.subMeshes) {
  19731. return;
  19732. }
  19733. this._unBindEffect();
  19734. },
  19735. enumerable: true,
  19736. configurable: true
  19737. });
  19738. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19739. /**
  19740. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19741. * @see http://doc.babylonjs.com/babylon101/shadows
  19742. */
  19743. get: function () {
  19744. return this._receiveShadows;
  19745. },
  19746. set: function (value) {
  19747. if (this._receiveShadows === value) {
  19748. return;
  19749. }
  19750. this._receiveShadows = value;
  19751. this._markSubMeshesAsLightDirty();
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19757. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19758. get: function () {
  19759. return this._hasVertexAlpha;
  19760. },
  19761. set: function (value) {
  19762. if (this._hasVertexAlpha === value) {
  19763. return;
  19764. }
  19765. this._hasVertexAlpha = value;
  19766. this._markSubMeshesAsAttributesDirty();
  19767. this._markSubMeshesAsMiscDirty();
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19773. /** 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) */
  19774. get: function () {
  19775. return this._useVertexColors;
  19776. },
  19777. set: function (value) {
  19778. if (this._useVertexColors === value) {
  19779. return;
  19780. }
  19781. this._useVertexColors = value;
  19782. this._markSubMeshesAsAttributesDirty();
  19783. },
  19784. enumerable: true,
  19785. configurable: true
  19786. });
  19787. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19788. /**
  19789. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19790. */
  19791. get: function () {
  19792. return this._computeBonesUsingShaders;
  19793. },
  19794. set: function (value) {
  19795. if (this._computeBonesUsingShaders === value) {
  19796. return;
  19797. }
  19798. this._computeBonesUsingShaders = value;
  19799. this._markSubMeshesAsAttributesDirty();
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19805. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19806. get: function () {
  19807. return this._numBoneInfluencers;
  19808. },
  19809. set: function (value) {
  19810. if (this._numBoneInfluencers === value) {
  19811. return;
  19812. }
  19813. this._numBoneInfluencers = value;
  19814. this._markSubMeshesAsAttributesDirty();
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19820. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19821. get: function () {
  19822. return this._applyFog;
  19823. },
  19824. set: function (value) {
  19825. if (this._applyFog === value) {
  19826. return;
  19827. }
  19828. this._applyFog = value;
  19829. this._markSubMeshesAsMiscDirty();
  19830. },
  19831. enumerable: true,
  19832. configurable: true
  19833. });
  19834. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19835. /**
  19836. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19837. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19838. */
  19839. get: function () {
  19840. return this._layerMask;
  19841. },
  19842. set: function (value) {
  19843. if (value === this._layerMask) {
  19844. return;
  19845. }
  19846. this._layerMask = value;
  19847. this._resyncLightSources();
  19848. },
  19849. enumerable: true,
  19850. configurable: true
  19851. });
  19852. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19853. /**
  19854. * Gets or sets a collision mask used to mask collisions (default is -1).
  19855. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19856. */
  19857. get: function () {
  19858. return this._collisionMask;
  19859. },
  19860. set: function (mask) {
  19861. this._collisionMask = !isNaN(mask) ? mask : -1;
  19862. },
  19863. enumerable: true,
  19864. configurable: true
  19865. });
  19866. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19867. /**
  19868. * Gets or sets the current collision group mask (-1 by default).
  19869. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19870. */
  19871. get: function () {
  19872. return this._collisionGroup;
  19873. },
  19874. set: function (mask) {
  19875. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19876. },
  19877. enumerable: true,
  19878. configurable: true
  19879. });
  19880. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19881. /** @hidden */
  19882. get: function () {
  19883. return null;
  19884. },
  19885. enumerable: true,
  19886. configurable: true
  19887. });
  19888. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19889. get: function () {
  19890. return this._skeleton;
  19891. },
  19892. /**
  19893. * Gets or sets a skeleton to apply skining transformations
  19894. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19895. */
  19896. set: function (value) {
  19897. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19898. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19899. }
  19900. if (value && value.needInitialSkinMatrix) {
  19901. value._registerMeshWithPoseMatrix(this);
  19902. }
  19903. this._skeleton = value;
  19904. if (!this._skeleton) {
  19905. this._bonesTransformMatrices = null;
  19906. }
  19907. this._markSubMeshesAsAttributesDirty();
  19908. },
  19909. enumerable: true,
  19910. configurable: true
  19911. });
  19912. /**
  19913. * Returns the string "AbstractMesh"
  19914. * @returns "AbstractMesh"
  19915. */
  19916. AbstractMesh.prototype.getClassName = function () {
  19917. return "AbstractMesh";
  19918. };
  19919. /**
  19920. * Gets a string representation of the current mesh
  19921. * @param fullDetails defines a boolean indicating if full details must be included
  19922. * @returns a string representation of the current mesh
  19923. */
  19924. AbstractMesh.prototype.toString = function (fullDetails) {
  19925. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19926. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19927. if (this._skeleton) {
  19928. ret += ", skeleton: " + this._skeleton.name;
  19929. }
  19930. if (fullDetails) {
  19931. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19932. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19933. }
  19934. return ret;
  19935. };
  19936. /** @hidden */
  19937. AbstractMesh.prototype._rebuild = function () {
  19938. if (this._occlusionQuery) {
  19939. this._occlusionQuery = null;
  19940. }
  19941. if (this._edgesRenderer) {
  19942. this._edgesRenderer._rebuild();
  19943. }
  19944. if (!this.subMeshes) {
  19945. return;
  19946. }
  19947. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19948. var subMesh = _a[_i];
  19949. subMesh._rebuild();
  19950. }
  19951. };
  19952. /** @hidden */
  19953. AbstractMesh.prototype._resyncLightSources = function () {
  19954. this._lightSources.length = 0;
  19955. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19956. var light = _a[_i];
  19957. if (!light.isEnabled()) {
  19958. continue;
  19959. }
  19960. if (light.canAffectMesh(this)) {
  19961. this._lightSources.push(light);
  19962. }
  19963. }
  19964. this._markSubMeshesAsLightDirty();
  19965. };
  19966. /** @hidden */
  19967. AbstractMesh.prototype._resyncLighSource = function (light) {
  19968. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19969. var index = this._lightSources.indexOf(light);
  19970. if (index === -1) {
  19971. if (!isIn) {
  19972. return;
  19973. }
  19974. this._lightSources.push(light);
  19975. }
  19976. else {
  19977. if (isIn) {
  19978. return;
  19979. }
  19980. this._lightSources.splice(index, 1);
  19981. }
  19982. this._markSubMeshesAsLightDirty();
  19983. };
  19984. /** @hidden */
  19985. AbstractMesh.prototype._unBindEffect = function () {
  19986. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19987. var subMesh = _a[_i];
  19988. subMesh.setEffect(null);
  19989. }
  19990. };
  19991. /** @hidden */
  19992. AbstractMesh.prototype._removeLightSource = function (light) {
  19993. var index = this._lightSources.indexOf(light);
  19994. if (index === -1) {
  19995. return;
  19996. }
  19997. this._lightSources.splice(index, 1);
  19998. this._markSubMeshesAsLightDirty();
  19999. };
  20000. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20001. if (!this.subMeshes) {
  20002. return;
  20003. }
  20004. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20005. var subMesh = _a[_i];
  20006. if (subMesh._materialDefines) {
  20007. func(subMesh._materialDefines);
  20008. }
  20009. }
  20010. };
  20011. /** @hidden */
  20012. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20013. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20014. };
  20015. /** @hidden */
  20016. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20017. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20018. };
  20019. /** @hidden */
  20020. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20021. if (!this.subMeshes) {
  20022. return;
  20023. }
  20024. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20025. var subMesh = _a[_i];
  20026. var material = subMesh.getMaterial();
  20027. if (material) {
  20028. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20029. }
  20030. }
  20031. };
  20032. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20033. /**
  20034. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20035. */
  20036. get: function () {
  20037. return this._scaling;
  20038. },
  20039. set: function (newScaling) {
  20040. this._scaling = newScaling;
  20041. if (this.physicsImpostor) {
  20042. this.physicsImpostor.forceUpdate();
  20043. }
  20044. },
  20045. enumerable: true,
  20046. configurable: true
  20047. });
  20048. // Methods
  20049. /**
  20050. * Disables the mesh edge rendering mode
  20051. * @returns the currentAbstractMesh
  20052. */
  20053. AbstractMesh.prototype.disableEdgesRendering = function () {
  20054. if (this._edgesRenderer) {
  20055. this._edgesRenderer.dispose();
  20056. this._edgesRenderer = null;
  20057. }
  20058. return this;
  20059. };
  20060. /**
  20061. * Enables the edge rendering mode on the mesh.
  20062. * This mode makes the mesh edges visible
  20063. * @param epsilon defines the maximal distance between two angles to detect a face
  20064. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20065. * @returns the currentAbstractMesh
  20066. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20067. */
  20068. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20069. if (epsilon === void 0) { epsilon = 0.95; }
  20070. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20071. this.disableEdgesRendering();
  20072. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20073. return this;
  20074. };
  20075. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20076. /**
  20077. * Gets the edgesRenderer associated with the mesh
  20078. */
  20079. get: function () {
  20080. return this._edgesRenderer;
  20081. },
  20082. enumerable: true,
  20083. configurable: true
  20084. });
  20085. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20086. /**
  20087. * Returns true if the mesh is blocked. Implemented by child classes
  20088. */
  20089. get: function () {
  20090. return false;
  20091. },
  20092. enumerable: true,
  20093. configurable: true
  20094. });
  20095. /**
  20096. * Returns the mesh itself by default. Implemented by child classes
  20097. * @param camera defines the camera to use to pick the right LOD level
  20098. * @returns the currentAbstractMesh
  20099. */
  20100. AbstractMesh.prototype.getLOD = function (camera) {
  20101. return this;
  20102. };
  20103. /**
  20104. * Returns 0 by default. Implemented by child classes
  20105. * @returns an integer
  20106. */
  20107. AbstractMesh.prototype.getTotalVertices = function () {
  20108. return 0;
  20109. };
  20110. /**
  20111. * Returns null by default. Implemented by child classes
  20112. * @returns null
  20113. */
  20114. AbstractMesh.prototype.getIndices = function () {
  20115. return null;
  20116. };
  20117. /**
  20118. * Returns the array of the requested vertex data kind. Implemented by child classes
  20119. * @param kind defines the vertex data kind to use
  20120. * @returns null
  20121. */
  20122. AbstractMesh.prototype.getVerticesData = function (kind) {
  20123. return null;
  20124. };
  20125. /**
  20126. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20127. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20128. * Note that a new underlying VertexBuffer object is created each call.
  20129. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20130. * @param kind defines vertex data kind:
  20131. * * BABYLON.VertexBuffer.PositionKind
  20132. * * BABYLON.VertexBuffer.UVKind
  20133. * * BABYLON.VertexBuffer.UV2Kind
  20134. * * BABYLON.VertexBuffer.UV3Kind
  20135. * * BABYLON.VertexBuffer.UV4Kind
  20136. * * BABYLON.VertexBuffer.UV5Kind
  20137. * * BABYLON.VertexBuffer.UV6Kind
  20138. * * BABYLON.VertexBuffer.ColorKind
  20139. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20140. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20141. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20142. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20143. * @param data defines the data source
  20144. * @param updatable defines if the data must be flagged as updatable (or static)
  20145. * @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
  20146. * @returns the current mesh
  20147. */
  20148. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20149. return this;
  20150. };
  20151. /**
  20152. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20153. * If the mesh has no geometry, it is simply returned as it is.
  20154. * @param kind defines vertex data kind:
  20155. * * BABYLON.VertexBuffer.PositionKind
  20156. * * BABYLON.VertexBuffer.UVKind
  20157. * * BABYLON.VertexBuffer.UV2Kind
  20158. * * BABYLON.VertexBuffer.UV3Kind
  20159. * * BABYLON.VertexBuffer.UV4Kind
  20160. * * BABYLON.VertexBuffer.UV5Kind
  20161. * * BABYLON.VertexBuffer.UV6Kind
  20162. * * BABYLON.VertexBuffer.ColorKind
  20163. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20164. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20165. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20166. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20167. * @param data defines the data source
  20168. * @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
  20169. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20170. * @returns the current mesh
  20171. */
  20172. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20173. return this;
  20174. };
  20175. /**
  20176. * Sets the mesh indices,
  20177. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20178. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20179. * @param totalVertices Defines the total number of vertices
  20180. * @returns the current mesh
  20181. */
  20182. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20183. return this;
  20184. };
  20185. /**
  20186. * Gets a boolean indicating if specific vertex data is present
  20187. * @param kind defines the vertex data kind to use
  20188. * @returns true is data kind is present
  20189. */
  20190. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20191. return false;
  20192. };
  20193. /**
  20194. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20195. * @returns a BoundingInfo
  20196. */
  20197. AbstractMesh.prototype.getBoundingInfo = function () {
  20198. if (this._masterMesh) {
  20199. return this._masterMesh.getBoundingInfo();
  20200. }
  20201. if (!this._boundingInfo) {
  20202. // this._boundingInfo is being created here
  20203. this._updateBoundingInfo();
  20204. }
  20205. // cannot be null.
  20206. return this._boundingInfo;
  20207. };
  20208. /**
  20209. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20210. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20211. * @returns the current mesh
  20212. */
  20213. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20214. if (includeDescendants === void 0) { includeDescendants = true; }
  20215. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20216. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20217. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20218. if (maxDimension === 0) {
  20219. return this;
  20220. }
  20221. var scale = 1 / maxDimension;
  20222. this.scaling.scaleInPlace(scale);
  20223. return this;
  20224. };
  20225. /**
  20226. * Overwrite the current bounding info
  20227. * @param boundingInfo defines the new bounding info
  20228. * @returns the current mesh
  20229. */
  20230. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20231. this._boundingInfo = boundingInfo;
  20232. return this;
  20233. };
  20234. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20235. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20236. get: function () {
  20237. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20238. },
  20239. enumerable: true,
  20240. configurable: true
  20241. });
  20242. /** @hidden */
  20243. AbstractMesh.prototype._preActivate = function () {
  20244. };
  20245. /** @hidden */
  20246. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20247. };
  20248. /** @hidden */
  20249. AbstractMesh.prototype._activate = function (renderId) {
  20250. this._renderId = renderId;
  20251. };
  20252. /**
  20253. * Gets the current world matrix
  20254. * @returns a Matrix
  20255. */
  20256. AbstractMesh.prototype.getWorldMatrix = function () {
  20257. if (this._masterMesh) {
  20258. return this._masterMesh.getWorldMatrix();
  20259. }
  20260. return _super.prototype.getWorldMatrix.call(this);
  20261. };
  20262. /** @hidden */
  20263. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20264. if (this._masterMesh) {
  20265. return this._masterMesh._getWorldMatrixDeterminant();
  20266. }
  20267. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20268. };
  20269. // ================================== Point of View Movement =================================
  20270. /**
  20271. * Perform relative position change from the point of view of behind the front of the mesh.
  20272. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20273. * Supports definition of mesh facing forward or backward
  20274. * @param amountRight defines the distance on the right axis
  20275. * @param amountUp defines the distance on the up axis
  20276. * @param amountForward defines the distance on the forward axis
  20277. * @returns the current mesh
  20278. */
  20279. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20280. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20281. return this;
  20282. };
  20283. /**
  20284. * Calculate relative position change from the point of view of behind the front of the mesh.
  20285. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20286. * Supports definition of mesh facing forward or backward
  20287. * @param amountRight defines the distance on the right axis
  20288. * @param amountUp defines the distance on the up axis
  20289. * @param amountForward defines the distance on the forward axis
  20290. * @returns the new displacement vector
  20291. */
  20292. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20293. var rotMatrix = new BABYLON.Matrix();
  20294. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20295. rotQuaternion.toRotationMatrix(rotMatrix);
  20296. var translationDelta = BABYLON.Vector3.Zero();
  20297. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20298. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20299. return translationDelta;
  20300. };
  20301. // ================================== Point of View Rotation =================================
  20302. /**
  20303. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20304. * Supports definition of mesh facing forward or backward
  20305. * @param flipBack defines the flip
  20306. * @param twirlClockwise defines the twirl
  20307. * @param tiltRight defines the tilt
  20308. * @returns the current mesh
  20309. */
  20310. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20311. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20312. return this;
  20313. };
  20314. /**
  20315. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20316. * Supports definition of mesh facing forward or backward.
  20317. * @param flipBack defines the flip
  20318. * @param twirlClockwise defines the twirl
  20319. * @param tiltRight defines the tilt
  20320. * @returns the new rotation vector
  20321. */
  20322. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20323. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20324. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20325. };
  20326. /**
  20327. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20328. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20329. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20330. * @returns the new bounding vectors
  20331. */
  20332. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20333. if (includeDescendants === void 0) { includeDescendants = true; }
  20334. if (predicate === void 0) { predicate = null; }
  20335. // Ensures that all world matrix will be recomputed.
  20336. this.getScene().incrementRenderId();
  20337. this.computeWorldMatrix(true);
  20338. var min;
  20339. var max;
  20340. var boundingInfo = this.getBoundingInfo();
  20341. if (!this.subMeshes) {
  20342. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20343. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20344. }
  20345. else {
  20346. min = boundingInfo.boundingBox.minimumWorld;
  20347. max = boundingInfo.boundingBox.maximumWorld;
  20348. }
  20349. if (includeDescendants) {
  20350. var descendants = this.getDescendants(false);
  20351. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20352. var descendant = descendants_1[_i];
  20353. var childMesh = descendant;
  20354. childMesh.computeWorldMatrix(true);
  20355. // Filters meshes based on custom predicate function.
  20356. if (predicate && !predicate(childMesh)) {
  20357. continue;
  20358. }
  20359. //make sure we have the needed params to get mix and max
  20360. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20361. continue;
  20362. }
  20363. var childBoundingInfo = childMesh.getBoundingInfo();
  20364. var boundingBox = childBoundingInfo.boundingBox;
  20365. var minBox = boundingBox.minimumWorld;
  20366. var maxBox = boundingBox.maximumWorld;
  20367. BABYLON.Tools.CheckExtends(minBox, min, max);
  20368. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20369. }
  20370. }
  20371. return {
  20372. min: min,
  20373. max: max
  20374. };
  20375. };
  20376. /** @hidden */
  20377. AbstractMesh.prototype._updateBoundingInfo = function () {
  20378. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20379. this._boundingInfo.update(this.worldMatrixFromCache);
  20380. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20381. return this;
  20382. };
  20383. /** @hidden */
  20384. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20385. if (!this.subMeshes) {
  20386. return this;
  20387. }
  20388. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20389. var subMesh = this.subMeshes[subIndex];
  20390. if (!subMesh.IsGlobal) {
  20391. subMesh.updateBoundingInfo(matrix);
  20392. }
  20393. }
  20394. return this;
  20395. };
  20396. /** @hidden */
  20397. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20398. // Bounding info
  20399. this._updateBoundingInfo();
  20400. };
  20401. /**
  20402. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20403. * A mesh is in the frustum if its bounding box intersects the frustum
  20404. * @param frustumPlanes defines the frustum to test
  20405. * @returns true if the mesh is in the frustum planes
  20406. */
  20407. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20408. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20409. };
  20410. /**
  20411. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20412. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20413. * @param frustumPlanes defines the frustum to test
  20414. * @returns true if the mesh is completely in the frustum planes
  20415. */
  20416. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20417. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20418. };
  20419. /**
  20420. * True if the mesh intersects another mesh or a SolidParticle object
  20421. * @param mesh defines a target mesh or SolidParticle to test
  20422. * @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)
  20423. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20424. * @returns true if there is an intersection
  20425. */
  20426. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20427. if (precise === void 0) { precise = false; }
  20428. if (!this._boundingInfo || !mesh._boundingInfo) {
  20429. return false;
  20430. }
  20431. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20432. return true;
  20433. }
  20434. if (includeDescendants) {
  20435. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20436. var child = _a[_i];
  20437. if (child.intersectsMesh(mesh, precise, true)) {
  20438. return true;
  20439. }
  20440. }
  20441. }
  20442. return false;
  20443. };
  20444. /**
  20445. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20446. * @param point defines the point to test
  20447. * @returns true if there is an intersection
  20448. */
  20449. AbstractMesh.prototype.intersectsPoint = function (point) {
  20450. if (!this._boundingInfo) {
  20451. return false;
  20452. }
  20453. return this._boundingInfo.intersectsPoint(point);
  20454. };
  20455. /**
  20456. * Gets the current physics impostor
  20457. * @see http://doc.babylonjs.com/features/physics_engine
  20458. * @returns a physics impostor or null
  20459. */
  20460. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20461. return this.physicsImpostor;
  20462. };
  20463. /**
  20464. * Gets the position of the current mesh in camera space
  20465. * @param camera defines the camera to use
  20466. * @returns a position
  20467. */
  20468. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20469. if (camera === void 0) { camera = null; }
  20470. if (!camera) {
  20471. camera = this.getScene().activeCamera;
  20472. }
  20473. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20474. };
  20475. /**
  20476. * Returns the distance from the mesh to the active camera
  20477. * @param camera defines the camera to use
  20478. * @returns the distance
  20479. */
  20480. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20481. if (camera === void 0) { camera = null; }
  20482. if (!camera) {
  20483. camera = this.getScene().activeCamera;
  20484. }
  20485. return this.absolutePosition.subtract(camera.position).length();
  20486. };
  20487. /**
  20488. * Apply a physic impulse to the mesh
  20489. * @param force defines the force to apply
  20490. * @param contactPoint defines where to apply the force
  20491. * @returns the current mesh
  20492. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20493. */
  20494. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20495. if (!this.physicsImpostor) {
  20496. return this;
  20497. }
  20498. this.physicsImpostor.applyImpulse(force, contactPoint);
  20499. return this;
  20500. };
  20501. /**
  20502. * Creates a physic joint between two meshes
  20503. * @param otherMesh defines the other mesh to use
  20504. * @param pivot1 defines the pivot to use on this mesh
  20505. * @param pivot2 defines the pivot to use on the other mesh
  20506. * @param options defines additional options (can be plugin dependent)
  20507. * @returns the current mesh
  20508. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20509. */
  20510. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20511. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20512. return this;
  20513. }
  20514. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20515. mainPivot: pivot1,
  20516. connectedPivot: pivot2,
  20517. nativeParams: options
  20518. });
  20519. return this;
  20520. };
  20521. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20522. // Collisions
  20523. /**
  20524. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20525. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20526. */
  20527. get: function () {
  20528. return this._checkCollisions;
  20529. },
  20530. set: function (collisionEnabled) {
  20531. this._checkCollisions = collisionEnabled;
  20532. if (this.getScene().workerCollisions) {
  20533. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20534. }
  20535. },
  20536. enumerable: true,
  20537. configurable: true
  20538. });
  20539. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20540. /**
  20541. * Gets Collider object used to compute collisions (not physics)
  20542. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20543. */
  20544. get: function () {
  20545. return this._collider;
  20546. },
  20547. enumerable: true,
  20548. configurable: true
  20549. });
  20550. /**
  20551. * Move the mesh using collision engine
  20552. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20553. * @param displacement defines the requested displacement vector
  20554. * @returns the current mesh
  20555. */
  20556. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20557. var globalPosition = this.getAbsolutePosition();
  20558. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20559. if (!this._collider) {
  20560. this._collider = new BABYLON.Collider();
  20561. }
  20562. this._collider._radius = this.ellipsoid;
  20563. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20564. return this;
  20565. };
  20566. // Submeshes octree
  20567. /**
  20568. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20569. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20570. * @param maxCapacity defines the maximum size of each block (64 by default)
  20571. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20572. * @returns the new octree
  20573. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20574. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20575. */
  20576. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20577. if (maxCapacity === void 0) { maxCapacity = 64; }
  20578. if (maxDepth === void 0) { maxDepth = 2; }
  20579. if (!this._submeshesOctree) {
  20580. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20581. }
  20582. this.computeWorldMatrix(true);
  20583. var boundingInfo = this.getBoundingInfo();
  20584. // Update octree
  20585. var bbox = boundingInfo.boundingBox;
  20586. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20587. return this._submeshesOctree;
  20588. };
  20589. // Collisions
  20590. /** @hidden */
  20591. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20592. this._generatePointsArray();
  20593. if (!this._positions) {
  20594. return this;
  20595. }
  20596. // Transformation
  20597. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20598. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20599. subMesh._lastColliderWorldVertices = [];
  20600. subMesh._trianglePlanes = [];
  20601. var start = subMesh.verticesStart;
  20602. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20603. for (var i = start; i < end; i++) {
  20604. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20605. }
  20606. }
  20607. // Collide
  20608. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20609. if (collider.collisionFound) {
  20610. collider.collidedMesh = this;
  20611. }
  20612. return this;
  20613. };
  20614. /** @hidden */
  20615. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20616. var subMeshes;
  20617. var len;
  20618. // Octrees
  20619. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20620. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20621. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20622. len = intersections.length;
  20623. subMeshes = intersections.data;
  20624. }
  20625. else {
  20626. subMeshes = this.subMeshes;
  20627. len = subMeshes.length;
  20628. }
  20629. for (var index = 0; index < len; index++) {
  20630. var subMesh = subMeshes[index];
  20631. // Bounding test
  20632. if (len > 1 && !subMesh._checkCollision(collider))
  20633. continue;
  20634. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20635. }
  20636. return this;
  20637. };
  20638. /** @hidden */
  20639. AbstractMesh.prototype._checkCollision = function (collider) {
  20640. // Bounding box test
  20641. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20642. return this;
  20643. // Transformation matrix
  20644. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20645. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20646. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20647. return this;
  20648. };
  20649. // Picking
  20650. /** @hidden */
  20651. AbstractMesh.prototype._generatePointsArray = function () {
  20652. return false;
  20653. };
  20654. /**
  20655. * Checks if the passed Ray intersects with the mesh
  20656. * @param ray defines the ray to use
  20657. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20658. * @returns the picking info
  20659. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20660. */
  20661. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20662. var pickingInfo = new BABYLON.PickingInfo();
  20663. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20664. return pickingInfo;
  20665. }
  20666. if (!this._generatePointsArray()) {
  20667. return pickingInfo;
  20668. }
  20669. var intersectInfo = null;
  20670. // Octrees
  20671. var subMeshes;
  20672. var len;
  20673. if (this._submeshesOctree && this.useOctreeForPicking) {
  20674. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20675. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20676. len = intersections.length;
  20677. subMeshes = intersections.data;
  20678. }
  20679. else {
  20680. subMeshes = this.subMeshes;
  20681. len = subMeshes.length;
  20682. }
  20683. for (var index = 0; index < len; index++) {
  20684. var subMesh = subMeshes[index];
  20685. // Bounding test
  20686. if (len > 1 && !subMesh.canIntersects(ray))
  20687. continue;
  20688. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20689. if (currentIntersectInfo) {
  20690. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20691. intersectInfo = currentIntersectInfo;
  20692. intersectInfo.subMeshId = index;
  20693. if (fastCheck) {
  20694. break;
  20695. }
  20696. }
  20697. }
  20698. }
  20699. if (intersectInfo) {
  20700. // Get picked point
  20701. var world = this.getWorldMatrix();
  20702. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20703. var direction = ray.direction.clone();
  20704. direction = direction.scale(intersectInfo.distance);
  20705. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20706. var pickedPoint = worldOrigin.add(worldDirection);
  20707. // Return result
  20708. pickingInfo.hit = true;
  20709. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20710. pickingInfo.pickedPoint = pickedPoint;
  20711. pickingInfo.pickedMesh = this;
  20712. pickingInfo.bu = intersectInfo.bu || 0;
  20713. pickingInfo.bv = intersectInfo.bv || 0;
  20714. pickingInfo.faceId = intersectInfo.faceId;
  20715. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20716. return pickingInfo;
  20717. }
  20718. return pickingInfo;
  20719. };
  20720. /**
  20721. * Clones the current mesh
  20722. * @param name defines the mesh name
  20723. * @param newParent defines the new mesh parent
  20724. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20725. * @returns the new mesh
  20726. */
  20727. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20728. return null;
  20729. };
  20730. /**
  20731. * Disposes all the submeshes of the current meshnp
  20732. * @returns the current mesh
  20733. */
  20734. AbstractMesh.prototype.releaseSubMeshes = function () {
  20735. if (this.subMeshes) {
  20736. while (this.subMeshes.length) {
  20737. this.subMeshes[0].dispose();
  20738. }
  20739. }
  20740. else {
  20741. this.subMeshes = new Array();
  20742. }
  20743. return this;
  20744. };
  20745. /**
  20746. * Releases resources associated with this abstract mesh.
  20747. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20748. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20749. */
  20750. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20751. var _this = this;
  20752. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20753. var index;
  20754. // Smart Array Retainers.
  20755. this.getScene().freeActiveMeshes();
  20756. this.getScene().freeRenderingGroups();
  20757. // Action manager
  20758. if (this.actionManager !== undefined && this.actionManager !== null) {
  20759. this.actionManager.dispose();
  20760. this.actionManager = null;
  20761. }
  20762. // Skeleton
  20763. this._skeleton = null;
  20764. // Physics
  20765. if (this.physicsImpostor) {
  20766. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20767. }
  20768. // Intersections in progress
  20769. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20770. var other = this._intersectionsInProgress[index];
  20771. var pos = other._intersectionsInProgress.indexOf(this);
  20772. other._intersectionsInProgress.splice(pos, 1);
  20773. }
  20774. this._intersectionsInProgress = [];
  20775. // Lights
  20776. var lights = this.getScene().lights;
  20777. lights.forEach(function (light) {
  20778. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20779. if (meshIndex !== -1) {
  20780. light.includedOnlyMeshes.splice(meshIndex, 1);
  20781. }
  20782. meshIndex = light.excludedMeshes.indexOf(_this);
  20783. if (meshIndex !== -1) {
  20784. light.excludedMeshes.splice(meshIndex, 1);
  20785. }
  20786. // Shadow generators
  20787. var generator = light.getShadowGenerator();
  20788. if (generator) {
  20789. var shadowMap = generator.getShadowMap();
  20790. if (shadowMap && shadowMap.renderList) {
  20791. meshIndex = shadowMap.renderList.indexOf(_this);
  20792. if (meshIndex !== -1) {
  20793. shadowMap.renderList.splice(meshIndex, 1);
  20794. }
  20795. }
  20796. }
  20797. });
  20798. // Edges
  20799. if (this._edgesRenderer) {
  20800. this._edgesRenderer.dispose();
  20801. this._edgesRenderer = null;
  20802. }
  20803. // SubMeshes
  20804. if (this.getClassName() !== "InstancedMesh") {
  20805. this.releaseSubMeshes();
  20806. }
  20807. // Octree
  20808. var sceneOctree = this.getScene().selectionOctree;
  20809. if (sceneOctree !== undefined && sceneOctree !== null) {
  20810. var index = sceneOctree.dynamicContent.indexOf(this);
  20811. if (index !== -1) {
  20812. sceneOctree.dynamicContent.splice(index, 1);
  20813. }
  20814. }
  20815. // Query
  20816. var engine = this.getScene().getEngine();
  20817. if (this._occlusionQuery) {
  20818. this._isOcclusionQueryInProgress = false;
  20819. engine.deleteQuery(this._occlusionQuery);
  20820. this._occlusionQuery = null;
  20821. }
  20822. // Engine
  20823. engine.wipeCaches();
  20824. // Remove from scene
  20825. this.getScene().removeMesh(this);
  20826. if (disposeMaterialAndTextures) {
  20827. if (this.material) {
  20828. this.material.dispose(false, true);
  20829. }
  20830. }
  20831. if (!doNotRecurse) {
  20832. // Particles
  20833. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20834. if (this.getScene().particleSystems[index].emitter === this) {
  20835. this.getScene().particleSystems[index].dispose();
  20836. index--;
  20837. }
  20838. }
  20839. }
  20840. // facet data
  20841. if (this._facetDataEnabled) {
  20842. this.disableFacetData();
  20843. }
  20844. this.onAfterWorldMatrixUpdateObservable.clear();
  20845. this.onCollideObservable.clear();
  20846. this.onCollisionPositionChangeObservable.clear();
  20847. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20848. };
  20849. /**
  20850. * Adds the passed mesh as a child to the current mesh
  20851. * @param mesh defines the child mesh
  20852. * @returns the current mesh
  20853. */
  20854. AbstractMesh.prototype.addChild = function (mesh) {
  20855. mesh.setParent(this);
  20856. return this;
  20857. };
  20858. /**
  20859. * Removes the passed mesh from the current mesh children list
  20860. * @param mesh defines the child mesh
  20861. * @returns the current mesh
  20862. */
  20863. AbstractMesh.prototype.removeChild = function (mesh) {
  20864. mesh.setParent(null);
  20865. return this;
  20866. };
  20867. // Facet data
  20868. /** @hidden */
  20869. AbstractMesh.prototype._initFacetData = function () {
  20870. if (!this._facetNormals) {
  20871. this._facetNormals = new Array();
  20872. }
  20873. if (!this._facetPositions) {
  20874. this._facetPositions = new Array();
  20875. }
  20876. if (!this._facetPartitioning) {
  20877. this._facetPartitioning = new Array();
  20878. }
  20879. this._facetNb = (this.getIndices().length / 3) | 0;
  20880. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20881. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20882. for (var f = 0; f < this._facetNb; f++) {
  20883. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20884. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20885. }
  20886. this._facetDataEnabled = true;
  20887. return this;
  20888. };
  20889. /**
  20890. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20891. * This method can be called within the render loop.
  20892. * 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
  20893. * @returns the current mesh
  20894. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20895. */
  20896. AbstractMesh.prototype.updateFacetData = function () {
  20897. if (!this._facetDataEnabled) {
  20898. this._initFacetData();
  20899. }
  20900. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20901. var indices = this.getIndices();
  20902. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20903. var bInfo = this.getBoundingInfo();
  20904. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20905. // init arrays, matrix and sort function on first call
  20906. this._facetDepthSortEnabled = true;
  20907. if (indices instanceof Uint16Array) {
  20908. this._depthSortedIndices = new Uint16Array(indices);
  20909. }
  20910. else if (indices instanceof Uint32Array) {
  20911. this._depthSortedIndices = new Uint32Array(indices);
  20912. }
  20913. else {
  20914. var needs32bits = false;
  20915. for (var i = 0; i < indices.length; i++) {
  20916. if (indices[i] > 65535) {
  20917. needs32bits = true;
  20918. break;
  20919. }
  20920. }
  20921. if (needs32bits) {
  20922. this._depthSortedIndices = new Uint32Array(indices);
  20923. }
  20924. else {
  20925. this._depthSortedIndices = new Uint16Array(indices);
  20926. }
  20927. }
  20928. this._facetDepthSortFunction = function (f1, f2) {
  20929. return (f2.sqDistance - f1.sqDistance);
  20930. };
  20931. if (!this._facetDepthSortFrom) {
  20932. var camera = this.getScene().activeCamera;
  20933. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20934. }
  20935. this._depthSortedFacets = [];
  20936. for (var f = 0; f < this._facetNb; f++) {
  20937. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20938. this._depthSortedFacets.push(depthSortedFacet);
  20939. }
  20940. this._invertedMatrix = BABYLON.Matrix.Identity();
  20941. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20942. }
  20943. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20944. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20945. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20946. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20947. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20948. this._subDiv.max = this._partitioningSubdivisions;
  20949. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20950. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20951. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20952. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20953. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20954. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20955. // set the parameters for ComputeNormals()
  20956. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20957. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20958. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20959. this._facetParameters.bInfo = bInfo;
  20960. this._facetParameters.bbSize = this._bbSize;
  20961. this._facetParameters.subDiv = this._subDiv;
  20962. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20963. this._facetParameters.depthSort = this._facetDepthSort;
  20964. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20965. this.computeWorldMatrix(true);
  20966. this._worldMatrix.invertToRef(this._invertedMatrix);
  20967. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20968. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20969. }
  20970. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20971. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20972. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20973. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20974. var l = (this._depthSortedIndices.length / 3) | 0;
  20975. for (var f = 0; f < l; f++) {
  20976. var sind = this._depthSortedFacets[f].ind;
  20977. this._depthSortedIndices[f * 3] = indices[sind];
  20978. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20979. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20980. }
  20981. this.updateIndices(this._depthSortedIndices);
  20982. }
  20983. return this;
  20984. };
  20985. /**
  20986. * Returns the facetLocalNormals array.
  20987. * The normals are expressed in the mesh local spac
  20988. * @returns an array of Vector3
  20989. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20990. */
  20991. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20992. if (!this._facetNormals) {
  20993. this.updateFacetData();
  20994. }
  20995. return this._facetNormals;
  20996. };
  20997. /**
  20998. * Returns the facetLocalPositions array.
  20999. * The facet positions are expressed in the mesh local space
  21000. * @returns an array of Vector3
  21001. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21002. */
  21003. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21004. if (!this._facetPositions) {
  21005. this.updateFacetData();
  21006. }
  21007. return this._facetPositions;
  21008. };
  21009. /**
  21010. * Returns the facetLocalPartioning array
  21011. * @returns an array of array of numbers
  21012. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21013. */
  21014. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21015. if (!this._facetPartitioning) {
  21016. this.updateFacetData();
  21017. }
  21018. return this._facetPartitioning;
  21019. };
  21020. /**
  21021. * Returns the i-th facet position in the world system.
  21022. * This method allocates a new Vector3 per call
  21023. * @param i defines the facet index
  21024. * @returns a new Vector3
  21025. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21026. */
  21027. AbstractMesh.prototype.getFacetPosition = function (i) {
  21028. var pos = BABYLON.Vector3.Zero();
  21029. this.getFacetPositionToRef(i, pos);
  21030. return pos;
  21031. };
  21032. /**
  21033. * Sets the reference Vector3 with the i-th facet position in the world system
  21034. * @param i defines the facet index
  21035. * @param ref defines the target vector
  21036. * @returns the current mesh
  21037. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21038. */
  21039. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21040. var localPos = (this.getFacetLocalPositions())[i];
  21041. var world = this.getWorldMatrix();
  21042. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21043. return this;
  21044. };
  21045. /**
  21046. * Returns the i-th facet normal in the world system.
  21047. * This method allocates a new Vector3 per call
  21048. * @param i defines the facet index
  21049. * @returns a new Vector3
  21050. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21051. */
  21052. AbstractMesh.prototype.getFacetNormal = function (i) {
  21053. var norm = BABYLON.Vector3.Zero();
  21054. this.getFacetNormalToRef(i, norm);
  21055. return norm;
  21056. };
  21057. /**
  21058. * Sets the reference Vector3 with the i-th facet normal in the world system
  21059. * @param i defines the facet index
  21060. * @param ref defines the target vector
  21061. * @returns the current mesh
  21062. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21063. */
  21064. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21065. var localNorm = (this.getFacetLocalNormals())[i];
  21066. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21067. return this;
  21068. };
  21069. /**
  21070. * 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)
  21071. * @param x defines x coordinate
  21072. * @param y defines y coordinate
  21073. * @param z defines z coordinate
  21074. * @returns the array of facet indexes
  21075. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21076. */
  21077. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21078. var bInfo = this.getBoundingInfo();
  21079. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21080. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21081. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21082. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21083. return null;
  21084. }
  21085. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21086. };
  21087. /**
  21088. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21089. * @param projected sets as the (x,y,z) world projection on the facet
  21090. * @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
  21091. * @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
  21092. * @param x defines x coordinate
  21093. * @param y defines y coordinate
  21094. * @param z defines z coordinate
  21095. * @returns the face index if found (or null instead)
  21096. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21097. */
  21098. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21099. if (checkFace === void 0) { checkFace = false; }
  21100. if (facing === void 0) { facing = true; }
  21101. var world = this.getWorldMatrix();
  21102. var invMat = BABYLON.Tmp.Matrix[5];
  21103. world.invertToRef(invMat);
  21104. var invVect = BABYLON.Tmp.Vector3[8];
  21105. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21106. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21107. if (projected) {
  21108. // tranform the local computed projected vector to world coordinates
  21109. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21110. }
  21111. return closest;
  21112. };
  21113. /**
  21114. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21115. * @param projected sets as the (x,y,z) local projection on the facet
  21116. * @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
  21117. * @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
  21118. * @param x defines x coordinate
  21119. * @param y defines y coordinate
  21120. * @param z defines z coordinate
  21121. * @returns the face index if found (or null instead)
  21122. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21123. */
  21124. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21125. if (checkFace === void 0) { checkFace = false; }
  21126. if (facing === void 0) { facing = true; }
  21127. var closest = null;
  21128. var tmpx = 0.0;
  21129. var tmpy = 0.0;
  21130. var tmpz = 0.0;
  21131. var d = 0.0; // tmp dot facet normal * facet position
  21132. var t0 = 0.0;
  21133. var projx = 0.0;
  21134. var projy = 0.0;
  21135. var projz = 0.0;
  21136. // Get all the facets in the same partitioning block than (x, y, z)
  21137. var facetPositions = this.getFacetLocalPositions();
  21138. var facetNormals = this.getFacetLocalNormals();
  21139. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21140. if (!facetsInBlock) {
  21141. return null;
  21142. }
  21143. // Get the closest facet to (x, y, z)
  21144. var shortest = Number.MAX_VALUE; // init distance vars
  21145. var tmpDistance = shortest;
  21146. var fib; // current facet in the block
  21147. var norm; // current facet normal
  21148. var p0; // current facet barycenter position
  21149. // loop on all the facets in the current partitioning block
  21150. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21151. fib = facetsInBlock[idx];
  21152. norm = facetNormals[fib];
  21153. p0 = facetPositions[fib];
  21154. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21155. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21156. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21157. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21158. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21159. projx = x + norm.x * t0;
  21160. projy = y + norm.y * t0;
  21161. projz = z + norm.z * t0;
  21162. tmpx = projx - x;
  21163. tmpy = projy - y;
  21164. tmpz = projz - z;
  21165. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21166. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21167. shortest = tmpDistance;
  21168. closest = fib;
  21169. if (projected) {
  21170. projected.x = projx;
  21171. projected.y = projy;
  21172. projected.z = projz;
  21173. }
  21174. }
  21175. }
  21176. }
  21177. return closest;
  21178. };
  21179. /**
  21180. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21181. * @returns the parameters
  21182. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21183. */
  21184. AbstractMesh.prototype.getFacetDataParameters = function () {
  21185. return this._facetParameters;
  21186. };
  21187. /**
  21188. * Disables the feature FacetData and frees the related memory
  21189. * @returns the current mesh
  21190. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21191. */
  21192. AbstractMesh.prototype.disableFacetData = function () {
  21193. if (this._facetDataEnabled) {
  21194. this._facetDataEnabled = false;
  21195. this._facetPositions = new Array();
  21196. this._facetNormals = new Array();
  21197. this._facetPartitioning = new Array();
  21198. this._facetParameters = null;
  21199. this._depthSortedIndices = new Uint32Array(0);
  21200. }
  21201. return this;
  21202. };
  21203. /**
  21204. * Updates the AbstractMesh indices array
  21205. * @param indices defines the data source
  21206. * @returns the current mesh
  21207. */
  21208. AbstractMesh.prototype.updateIndices = function (indices) {
  21209. return this;
  21210. };
  21211. /**
  21212. * Creates new normals data for the mesh
  21213. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21214. * @returns the current mesh
  21215. */
  21216. AbstractMesh.prototype.createNormals = function (updatable) {
  21217. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21218. var indices = this.getIndices();
  21219. var normals;
  21220. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21221. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21222. }
  21223. else {
  21224. normals = [];
  21225. }
  21226. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21227. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21228. return this;
  21229. };
  21230. /**
  21231. * Align the mesh with a normal
  21232. * @param normal defines the normal to use
  21233. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21234. * @returns the current mesh
  21235. */
  21236. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21237. if (!upDirection) {
  21238. upDirection = BABYLON.Axis.Y;
  21239. }
  21240. var axisX = BABYLON.Tmp.Vector3[0];
  21241. var axisZ = BABYLON.Tmp.Vector3[1];
  21242. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21243. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21244. if (this.rotationQuaternion) {
  21245. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21246. }
  21247. else {
  21248. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21249. }
  21250. return this;
  21251. };
  21252. /** @hidden */
  21253. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21254. var engine = this.getEngine();
  21255. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21256. this._isOccluded = false;
  21257. return;
  21258. }
  21259. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21260. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21261. if (isOcclusionQueryAvailable) {
  21262. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21263. this._isOcclusionQueryInProgress = false;
  21264. this._occlusionInternalRetryCounter = 0;
  21265. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21266. }
  21267. else {
  21268. this._occlusionInternalRetryCounter++;
  21269. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21270. this._isOcclusionQueryInProgress = false;
  21271. this._occlusionInternalRetryCounter = 0;
  21272. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21273. // if strict continue the last state of the object.
  21274. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21275. }
  21276. else {
  21277. return;
  21278. }
  21279. }
  21280. }
  21281. var scene = this.getScene();
  21282. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21283. if (!this._occlusionQuery) {
  21284. this._occlusionQuery = engine.createQuery();
  21285. }
  21286. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21287. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21288. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21289. this._isOcclusionQueryInProgress = true;
  21290. };
  21291. /** No occlusion */
  21292. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21293. /** Occlusion set to optimisitic */
  21294. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21295. /** Occlusion set to strict */
  21296. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21297. /** Use an accurante occlusion algorithm */
  21298. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21299. /** Use a conservative occlusion algorithm */
  21300. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21301. return AbstractMesh;
  21302. }(BABYLON.TransformNode));
  21303. BABYLON.AbstractMesh = AbstractMesh;
  21304. })(BABYLON || (BABYLON = {}));
  21305. //# sourceMappingURL=babylon.abstractMesh.js.map
  21306. var BABYLON;
  21307. (function (BABYLON) {
  21308. /**
  21309. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21310. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21311. * 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.
  21312. */
  21313. var Light = /** @class */ (function (_super) {
  21314. __extends(Light, _super);
  21315. /**
  21316. * Creates a Light object in the scene.
  21317. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21318. * @param name The firendly name of the light
  21319. * @param scene The scene the light belongs too
  21320. */
  21321. function Light(name, scene) {
  21322. var _this = _super.call(this, name, scene) || this;
  21323. /**
  21324. * Diffuse gives the basic color to an object.
  21325. */
  21326. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21327. /**
  21328. * Specular produces a highlight color on an object.
  21329. * Note: This is note affecting PBR materials.
  21330. */
  21331. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21332. /**
  21333. * Strength of the light.
  21334. * Note: By default it is define in the framework own unit.
  21335. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21336. */
  21337. _this.intensity = 1.0;
  21338. /**
  21339. * Defines how far from the source the light is impacting in scene units.
  21340. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21341. */
  21342. _this.range = Number.MAX_VALUE;
  21343. /**
  21344. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21345. * of light.
  21346. */
  21347. _this._photometricScale = 1.0;
  21348. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21349. _this._radius = 0.00001;
  21350. /**
  21351. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21352. * exceeding the number allowed of the materials.
  21353. */
  21354. _this.renderPriority = 0;
  21355. _this._shadowEnabled = true;
  21356. _this._excludeWithLayerMask = 0;
  21357. _this._includeOnlyWithLayerMask = 0;
  21358. _this._lightmapMode = 0;
  21359. /**
  21360. * @hidden Internal use only.
  21361. */
  21362. _this._excludedMeshesIds = new Array();
  21363. /**
  21364. * @hidden Internal use only.
  21365. */
  21366. _this._includedOnlyMeshesIds = new Array();
  21367. _this.getScene().addLight(_this);
  21368. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21369. _this._buildUniformLayout();
  21370. _this.includedOnlyMeshes = new Array();
  21371. _this.excludedMeshes = new Array();
  21372. _this._resyncMeshes();
  21373. return _this;
  21374. }
  21375. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21376. /**
  21377. * If every light affecting the material is in this lightmapMode,
  21378. * material.lightmapTexture adds or multiplies
  21379. * (depends on material.useLightmapAsShadowmap)
  21380. * after every other light calculations.
  21381. */
  21382. get: function () {
  21383. return Light._LIGHTMAP_DEFAULT;
  21384. },
  21385. enumerable: true,
  21386. configurable: true
  21387. });
  21388. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21389. /**
  21390. * material.lightmapTexture as only diffuse lighting from this light
  21391. * adds only specular lighting from this light
  21392. * adds dynamic shadows
  21393. */
  21394. get: function () {
  21395. return Light._LIGHTMAP_SPECULAR;
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21401. /**
  21402. * material.lightmapTexture as only lighting
  21403. * no light calculation from this light
  21404. * only adds dynamic shadows from this light
  21405. */
  21406. get: function () {
  21407. return Light._LIGHTMAP_SHADOWSONLY;
  21408. },
  21409. enumerable: true,
  21410. configurable: true
  21411. });
  21412. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21413. /**
  21414. * Each light type uses the default quantity according to its type:
  21415. * point/spot lights use luminous intensity
  21416. * directional lights use illuminance
  21417. */
  21418. get: function () {
  21419. return Light._INTENSITYMODE_AUTOMATIC;
  21420. },
  21421. enumerable: true,
  21422. configurable: true
  21423. });
  21424. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21425. /**
  21426. * lumen (lm)
  21427. */
  21428. get: function () {
  21429. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21430. },
  21431. enumerable: true,
  21432. configurable: true
  21433. });
  21434. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21435. /**
  21436. * candela (lm/sr)
  21437. */
  21438. get: function () {
  21439. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21440. },
  21441. enumerable: true,
  21442. configurable: true
  21443. });
  21444. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21445. /**
  21446. * lux (lm/m^2)
  21447. */
  21448. get: function () {
  21449. return Light._INTENSITYMODE_ILLUMINANCE;
  21450. },
  21451. enumerable: true,
  21452. configurable: true
  21453. });
  21454. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21455. /**
  21456. * nit (cd/m^2)
  21457. */
  21458. get: function () {
  21459. return Light._INTENSITYMODE_LUMINANCE;
  21460. },
  21461. enumerable: true,
  21462. configurable: true
  21463. });
  21464. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21465. /**
  21466. * Light type const id of the point light.
  21467. */
  21468. get: function () {
  21469. return Light._LIGHTTYPEID_POINTLIGHT;
  21470. },
  21471. enumerable: true,
  21472. configurable: true
  21473. });
  21474. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21475. /**
  21476. * Light type const id of the directional light.
  21477. */
  21478. get: function () {
  21479. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21480. },
  21481. enumerable: true,
  21482. configurable: true
  21483. });
  21484. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21485. /**
  21486. * Light type const id of the spot light.
  21487. */
  21488. get: function () {
  21489. return Light._LIGHTTYPEID_SPOTLIGHT;
  21490. },
  21491. enumerable: true,
  21492. configurable: true
  21493. });
  21494. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21495. /**
  21496. * Light type const id of the hemispheric light.
  21497. */
  21498. get: function () {
  21499. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21500. },
  21501. enumerable: true,
  21502. configurable: true
  21503. });
  21504. Object.defineProperty(Light.prototype, "intensityMode", {
  21505. /**
  21506. * Gets the photometric scale used to interpret the intensity.
  21507. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21508. */
  21509. get: function () {
  21510. return this._intensityMode;
  21511. },
  21512. /**
  21513. * Sets the photometric scale used to interpret the intensity.
  21514. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21515. */
  21516. set: function (value) {
  21517. this._intensityMode = value;
  21518. this._computePhotometricScale();
  21519. },
  21520. enumerable: true,
  21521. configurable: true
  21522. });
  21523. ;
  21524. ;
  21525. Object.defineProperty(Light.prototype, "radius", {
  21526. /**
  21527. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21528. */
  21529. get: function () {
  21530. return this._radius;
  21531. },
  21532. /**
  21533. * sets the light radius used by PBR Materials to simulate soft area lights.
  21534. */
  21535. set: function (value) {
  21536. this._radius = value;
  21537. this._computePhotometricScale();
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. ;
  21543. ;
  21544. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21545. /**
  21546. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21547. * the current shadow generator.
  21548. */
  21549. get: function () {
  21550. return this._shadowEnabled;
  21551. },
  21552. /**
  21553. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21554. * the current shadow generator.
  21555. */
  21556. set: function (value) {
  21557. if (this._shadowEnabled === value) {
  21558. return;
  21559. }
  21560. this._shadowEnabled = value;
  21561. this._markMeshesAsLightDirty();
  21562. },
  21563. enumerable: true,
  21564. configurable: true
  21565. });
  21566. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21567. /**
  21568. * Gets the only meshes impacted by this light.
  21569. */
  21570. get: function () {
  21571. return this._includedOnlyMeshes;
  21572. },
  21573. /**
  21574. * Sets the only meshes impacted by this light.
  21575. */
  21576. set: function (value) {
  21577. this._includedOnlyMeshes = value;
  21578. this._hookArrayForIncludedOnly(value);
  21579. },
  21580. enumerable: true,
  21581. configurable: true
  21582. });
  21583. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21584. /**
  21585. * Gets the meshes not impacted by this light.
  21586. */
  21587. get: function () {
  21588. return this._excludedMeshes;
  21589. },
  21590. /**
  21591. * Sets the meshes not impacted by this light.
  21592. */
  21593. set: function (value) {
  21594. this._excludedMeshes = value;
  21595. this._hookArrayForExcluded(value);
  21596. },
  21597. enumerable: true,
  21598. configurable: true
  21599. });
  21600. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21601. /**
  21602. * Gets the layer id use to find what meshes are not impacted by the light.
  21603. * Inactive if 0
  21604. */
  21605. get: function () {
  21606. return this._excludeWithLayerMask;
  21607. },
  21608. /**
  21609. * Sets the layer id use to find what meshes are not impacted by the light.
  21610. * Inactive if 0
  21611. */
  21612. set: function (value) {
  21613. this._excludeWithLayerMask = value;
  21614. this._resyncMeshes();
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21620. /**
  21621. * Gets the layer id use to find what meshes are impacted by the light.
  21622. * Inactive if 0
  21623. */
  21624. get: function () {
  21625. return this._includeOnlyWithLayerMask;
  21626. },
  21627. /**
  21628. * Sets the layer id use to find what meshes are impacted by the light.
  21629. * Inactive if 0
  21630. */
  21631. set: function (value) {
  21632. this._includeOnlyWithLayerMask = value;
  21633. this._resyncMeshes();
  21634. },
  21635. enumerable: true,
  21636. configurable: true
  21637. });
  21638. Object.defineProperty(Light.prototype, "lightmapMode", {
  21639. /**
  21640. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21641. */
  21642. get: function () {
  21643. return this._lightmapMode;
  21644. },
  21645. /**
  21646. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21647. */
  21648. set: function (value) {
  21649. if (this._lightmapMode === value) {
  21650. return;
  21651. }
  21652. this._lightmapMode = value;
  21653. this._markMeshesAsLightDirty();
  21654. },
  21655. enumerable: true,
  21656. configurable: true
  21657. });
  21658. /**
  21659. * Returns the string "Light".
  21660. * @returns the class name
  21661. */
  21662. Light.prototype.getClassName = function () {
  21663. return "Light";
  21664. };
  21665. /**
  21666. * Converts the light information to a readable string for debug purpose.
  21667. * @param fullDetails Supports for multiple levels of logging within scene loading
  21668. * @returns the human readable light info
  21669. */
  21670. Light.prototype.toString = function (fullDetails) {
  21671. var ret = "Name: " + this.name;
  21672. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21673. if (this.animations) {
  21674. for (var i = 0; i < this.animations.length; i++) {
  21675. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21676. }
  21677. }
  21678. if (fullDetails) {
  21679. }
  21680. return ret;
  21681. };
  21682. /**
  21683. * Set the enabled state of this node.
  21684. * @param value - the new enabled state
  21685. */
  21686. Light.prototype.setEnabled = function (value) {
  21687. _super.prototype.setEnabled.call(this, value);
  21688. this._resyncMeshes();
  21689. };
  21690. /**
  21691. * Returns the Light associated shadow generator if any.
  21692. * @return the associated shadow generator.
  21693. */
  21694. Light.prototype.getShadowGenerator = function () {
  21695. return this._shadowGenerator;
  21696. };
  21697. /**
  21698. * Returns a Vector3, the absolute light position in the World.
  21699. * @returns the world space position of the light
  21700. */
  21701. Light.prototype.getAbsolutePosition = function () {
  21702. return BABYLON.Vector3.Zero();
  21703. };
  21704. /**
  21705. * Specifies if the light will affect the passed mesh.
  21706. * @param mesh The mesh to test against the light
  21707. * @return true the mesh is affected otherwise, false.
  21708. */
  21709. Light.prototype.canAffectMesh = function (mesh) {
  21710. if (!mesh) {
  21711. return true;
  21712. }
  21713. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21714. return false;
  21715. }
  21716. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21717. return false;
  21718. }
  21719. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21720. return false;
  21721. }
  21722. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21723. return false;
  21724. }
  21725. return true;
  21726. };
  21727. /**
  21728. * Computes and Returns the light World matrix.
  21729. * @returns the world matrix
  21730. */
  21731. Light.prototype.getWorldMatrix = function () {
  21732. this._currentRenderId = this.getScene().getRenderId();
  21733. this._childRenderId = this._currentRenderId;
  21734. var worldMatrix = this._getWorldMatrix();
  21735. if (this.parent && this.parent.getWorldMatrix) {
  21736. if (!this._parentedWorldMatrix) {
  21737. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21738. }
  21739. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21740. this._markSyncedWithParent();
  21741. return this._parentedWorldMatrix;
  21742. }
  21743. return worldMatrix;
  21744. };
  21745. /**
  21746. * Sort function to order lights for rendering.
  21747. * @param a First Light object to compare to second.
  21748. * @param b Second Light object to compare first.
  21749. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21750. */
  21751. Light.CompareLightsPriority = function (a, b) {
  21752. //shadow-casting lights have priority over non-shadow-casting lights
  21753. //the renderPrioirty is a secondary sort criterion
  21754. if (a.shadowEnabled !== b.shadowEnabled) {
  21755. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21756. }
  21757. return b.renderPriority - a.renderPriority;
  21758. };
  21759. /**
  21760. * Releases resources associated with this node.
  21761. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21762. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21763. */
  21764. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21765. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21766. if (this._shadowGenerator) {
  21767. this._shadowGenerator.dispose();
  21768. this._shadowGenerator = null;
  21769. }
  21770. // Animations
  21771. this.getScene().stopAnimation(this);
  21772. // Remove from meshes
  21773. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21774. var mesh = _a[_i];
  21775. mesh._removeLightSource(this);
  21776. }
  21777. this._uniformBuffer.dispose();
  21778. // Remove from scene
  21779. this.getScene().removeLight(this);
  21780. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21781. };
  21782. /**
  21783. * Returns the light type ID (integer).
  21784. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21785. */
  21786. Light.prototype.getTypeID = function () {
  21787. return 0;
  21788. };
  21789. /**
  21790. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21791. * @returns the scaled intensity in intensity mode unit
  21792. */
  21793. Light.prototype.getScaledIntensity = function () {
  21794. return this._photometricScale * this.intensity;
  21795. };
  21796. /**
  21797. * Returns a new Light object, named "name", from the current one.
  21798. * @param name The name of the cloned light
  21799. * @returns the new created light
  21800. */
  21801. Light.prototype.clone = function (name) {
  21802. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21803. if (!constructor) {
  21804. return null;
  21805. }
  21806. return BABYLON.SerializationHelper.Clone(constructor, this);
  21807. };
  21808. /**
  21809. * Serializes the current light into a Serialization object.
  21810. * @returns the serialized object.
  21811. */
  21812. Light.prototype.serialize = function () {
  21813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21814. // Type
  21815. serializationObject.type = this.getTypeID();
  21816. // Parent
  21817. if (this.parent) {
  21818. serializationObject.parentId = this.parent.id;
  21819. }
  21820. // Inclusion / exclusions
  21821. if (this.excludedMeshes.length > 0) {
  21822. serializationObject.excludedMeshesIds = [];
  21823. this.excludedMeshes.forEach(function (mesh) {
  21824. serializationObject.excludedMeshesIds.push(mesh.id);
  21825. });
  21826. }
  21827. if (this.includedOnlyMeshes.length > 0) {
  21828. serializationObject.includedOnlyMeshesIds = [];
  21829. this.includedOnlyMeshes.forEach(function (mesh) {
  21830. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21831. });
  21832. }
  21833. // Animations
  21834. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21835. serializationObject.ranges = this.serializeAnimationRanges();
  21836. return serializationObject;
  21837. };
  21838. /**
  21839. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21840. * This new light is named "name" and added to the passed scene.
  21841. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21842. * @param name The friendly name of the light
  21843. * @param scene The scene the new light will belong to
  21844. * @returns the constructor function
  21845. */
  21846. Light.GetConstructorFromName = function (type, name, scene) {
  21847. switch (type) {
  21848. case 0:
  21849. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21850. case 1:
  21851. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21852. case 2:
  21853. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21854. case 3:
  21855. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21856. }
  21857. return null;
  21858. };
  21859. /**
  21860. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21861. * @param parsedLight The JSON representation of the light
  21862. * @param scene The scene to create the parsed light in
  21863. * @returns the created light after parsing
  21864. */
  21865. Light.Parse = function (parsedLight, scene) {
  21866. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21867. if (!constructor) {
  21868. return null;
  21869. }
  21870. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21871. // Inclusion / exclusions
  21872. if (parsedLight.excludedMeshesIds) {
  21873. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21874. }
  21875. if (parsedLight.includedOnlyMeshesIds) {
  21876. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21877. }
  21878. // Parent
  21879. if (parsedLight.parentId) {
  21880. light._waitingParentId = parsedLight.parentId;
  21881. }
  21882. // Animations
  21883. if (parsedLight.animations) {
  21884. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21885. var parsedAnimation = parsedLight.animations[animationIndex];
  21886. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21887. }
  21888. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21889. }
  21890. if (parsedLight.autoAnimate) {
  21891. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21892. }
  21893. return light;
  21894. };
  21895. Light.prototype._hookArrayForExcluded = function (array) {
  21896. var _this = this;
  21897. var oldPush = array.push;
  21898. array.push = function () {
  21899. var items = [];
  21900. for (var _i = 0; _i < arguments.length; _i++) {
  21901. items[_i] = arguments[_i];
  21902. }
  21903. var result = oldPush.apply(array, items);
  21904. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21905. var item = items_1[_a];
  21906. item._resyncLighSource(_this);
  21907. }
  21908. return result;
  21909. };
  21910. var oldSplice = array.splice;
  21911. array.splice = function (index, deleteCount) {
  21912. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21913. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21914. var item = deleted_1[_i];
  21915. item._resyncLighSource(_this);
  21916. }
  21917. return deleted;
  21918. };
  21919. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21920. var item = array_1[_i];
  21921. item._resyncLighSource(this);
  21922. }
  21923. };
  21924. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21925. var _this = this;
  21926. var oldPush = array.push;
  21927. array.push = function () {
  21928. var items = [];
  21929. for (var _i = 0; _i < arguments.length; _i++) {
  21930. items[_i] = arguments[_i];
  21931. }
  21932. var result = oldPush.apply(array, items);
  21933. _this._resyncMeshes();
  21934. return result;
  21935. };
  21936. var oldSplice = array.splice;
  21937. array.splice = function (index, deleteCount) {
  21938. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21939. _this._resyncMeshes();
  21940. return deleted;
  21941. };
  21942. this._resyncMeshes();
  21943. };
  21944. Light.prototype._resyncMeshes = function () {
  21945. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21946. var mesh = _a[_i];
  21947. mesh._resyncLighSource(this);
  21948. }
  21949. };
  21950. /**
  21951. * Forces the meshes to update their light related information in their rendering used effects
  21952. * @hidden Internal Use Only
  21953. */
  21954. Light.prototype._markMeshesAsLightDirty = function () {
  21955. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21956. var mesh = _a[_i];
  21957. if (mesh._lightSources.indexOf(this) !== -1) {
  21958. mesh._markSubMeshesAsLightDirty();
  21959. }
  21960. }
  21961. };
  21962. /**
  21963. * Recomputes the cached photometric scale if needed.
  21964. */
  21965. Light.prototype._computePhotometricScale = function () {
  21966. this._photometricScale = this._getPhotometricScale();
  21967. this.getScene().resetCachedMaterial();
  21968. };
  21969. /**
  21970. * Returns the Photometric Scale according to the light type and intensity mode.
  21971. */
  21972. Light.prototype._getPhotometricScale = function () {
  21973. var photometricScale = 0.0;
  21974. var lightTypeID = this.getTypeID();
  21975. //get photometric mode
  21976. var photometricMode = this.intensityMode;
  21977. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21978. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21979. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21980. }
  21981. else {
  21982. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21983. }
  21984. }
  21985. //compute photometric scale
  21986. switch (lightTypeID) {
  21987. case Light.LIGHTTYPEID_POINTLIGHT:
  21988. case Light.LIGHTTYPEID_SPOTLIGHT:
  21989. switch (photometricMode) {
  21990. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21991. photometricScale = 1.0 / (4.0 * Math.PI);
  21992. break;
  21993. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21994. photometricScale = 1.0;
  21995. break;
  21996. case Light.INTENSITYMODE_LUMINANCE:
  21997. photometricScale = this.radius * this.radius;
  21998. break;
  21999. }
  22000. break;
  22001. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22002. switch (photometricMode) {
  22003. case Light.INTENSITYMODE_ILLUMINANCE:
  22004. photometricScale = 1.0;
  22005. break;
  22006. case Light.INTENSITYMODE_LUMINANCE:
  22007. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22008. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22009. var apexAngleRadians = this.radius;
  22010. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22011. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22012. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22013. photometricScale = solidAngle;
  22014. break;
  22015. }
  22016. break;
  22017. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22018. // No fall off in hemisperic light.
  22019. photometricScale = 1.0;
  22020. break;
  22021. }
  22022. return photometricScale;
  22023. };
  22024. /**
  22025. * Reorder the light in the scene according to their defined priority.
  22026. * @hidden Internal Use Only
  22027. */
  22028. Light.prototype._reorderLightsInScene = function () {
  22029. var scene = this.getScene();
  22030. if (this._renderPriority != 0) {
  22031. scene.requireLightSorting = true;
  22032. }
  22033. this.getScene().sortLightsByPriority();
  22034. };
  22035. //lightmapMode Consts
  22036. Light._LIGHTMAP_DEFAULT = 0;
  22037. Light._LIGHTMAP_SPECULAR = 1;
  22038. Light._LIGHTMAP_SHADOWSONLY = 2;
  22039. // Intensity Mode Consts
  22040. Light._INTENSITYMODE_AUTOMATIC = 0;
  22041. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22042. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22043. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22044. Light._INTENSITYMODE_LUMINANCE = 4;
  22045. // Light types ids const.
  22046. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22047. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22048. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22049. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22050. __decorate([
  22051. BABYLON.serializeAsColor3()
  22052. ], Light.prototype, "diffuse", void 0);
  22053. __decorate([
  22054. BABYLON.serializeAsColor3()
  22055. ], Light.prototype, "specular", void 0);
  22056. __decorate([
  22057. BABYLON.serialize()
  22058. ], Light.prototype, "intensity", void 0);
  22059. __decorate([
  22060. BABYLON.serialize()
  22061. ], Light.prototype, "range", void 0);
  22062. __decorate([
  22063. BABYLON.serialize()
  22064. ], Light.prototype, "intensityMode", null);
  22065. __decorate([
  22066. BABYLON.serialize()
  22067. ], Light.prototype, "radius", null);
  22068. __decorate([
  22069. BABYLON.serialize()
  22070. ], Light.prototype, "_renderPriority", void 0);
  22071. __decorate([
  22072. BABYLON.expandToProperty("_reorderLightsInScene")
  22073. ], Light.prototype, "renderPriority", void 0);
  22074. __decorate([
  22075. BABYLON.serialize("shadowEnabled")
  22076. ], Light.prototype, "_shadowEnabled", void 0);
  22077. __decorate([
  22078. BABYLON.serialize("excludeWithLayerMask")
  22079. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22080. __decorate([
  22081. BABYLON.serialize("includeOnlyWithLayerMask")
  22082. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22083. __decorate([
  22084. BABYLON.serialize("lightmapMode")
  22085. ], Light.prototype, "_lightmapMode", void 0);
  22086. return Light;
  22087. }(BABYLON.Node));
  22088. BABYLON.Light = Light;
  22089. })(BABYLON || (BABYLON = {}));
  22090. //# sourceMappingURL=babylon.light.js.map
  22091. var BABYLON;
  22092. (function (BABYLON) {
  22093. var Camera = /** @class */ (function (_super) {
  22094. __extends(Camera, _super);
  22095. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22096. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22097. var _this = _super.call(this, name, scene) || this;
  22098. /**
  22099. * The vector the camera should consider as up.
  22100. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22101. */
  22102. _this.upVector = BABYLON.Vector3.Up();
  22103. _this.orthoLeft = null;
  22104. _this.orthoRight = null;
  22105. _this.orthoBottom = null;
  22106. _this.orthoTop = null;
  22107. /**
  22108. * FOV is set in Radians. (default is 0.8)
  22109. */
  22110. _this.fov = 0.8;
  22111. _this.minZ = 1;
  22112. _this.maxZ = 10000.0;
  22113. _this.inertia = 0.9;
  22114. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22115. _this.isIntermediate = false;
  22116. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22117. /**
  22118. * Restricts the camera to viewing objects with the same layerMask.
  22119. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22120. */
  22121. _this.layerMask = 0x0FFFFFFF;
  22122. /**
  22123. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22124. */
  22125. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22126. // Camera rig members
  22127. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22128. _this._rigCameras = new Array();
  22129. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22130. _this._skipRendering = false;
  22131. _this.customRenderTargets = new Array();
  22132. // Observables
  22133. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22134. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22135. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22136. _this.onRestoreStateObservable = new BABYLON.Observable();
  22137. // Cache
  22138. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22139. _this._projectionMatrix = new BABYLON.Matrix();
  22140. _this._doNotComputeProjectionMatrix = false;
  22141. _this._worldMatrix = BABYLON.Matrix.Identity();
  22142. _this._postProcesses = new Array();
  22143. _this._transformMatrix = BABYLON.Matrix.Zero();
  22144. _this._activeMeshes = new BABYLON.SmartArray(256);
  22145. _this._globalPosition = BABYLON.Vector3.Zero();
  22146. _this._refreshFrustumPlanes = true;
  22147. _this.getScene().addCamera(_this);
  22148. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22149. _this.getScene().activeCamera = _this;
  22150. }
  22151. _this.position = position;
  22152. return _this;
  22153. }
  22154. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22155. get: function () {
  22156. return Camera._PERSPECTIVE_CAMERA;
  22157. },
  22158. enumerable: true,
  22159. configurable: true
  22160. });
  22161. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22162. get: function () {
  22163. return Camera._ORTHOGRAPHIC_CAMERA;
  22164. },
  22165. enumerable: true,
  22166. configurable: true
  22167. });
  22168. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22169. /**
  22170. * This is the default FOV mode for perspective cameras.
  22171. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22172. *
  22173. */
  22174. get: function () {
  22175. return Camera._FOVMODE_VERTICAL_FIXED;
  22176. },
  22177. enumerable: true,
  22178. configurable: true
  22179. });
  22180. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22181. /**
  22182. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22183. *
  22184. */
  22185. get: function () {
  22186. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22192. get: function () {
  22193. return Camera._RIG_MODE_NONE;
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22199. get: function () {
  22200. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22201. },
  22202. enumerable: true,
  22203. configurable: true
  22204. });
  22205. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22206. get: function () {
  22207. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22213. get: function () {
  22214. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22220. get: function () {
  22221. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22222. },
  22223. enumerable: true,
  22224. configurable: true
  22225. });
  22226. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22227. get: function () {
  22228. return Camera._RIG_MODE_VR;
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22234. get: function () {
  22235. return Camera._RIG_MODE_WEBVR;
  22236. },
  22237. enumerable: true,
  22238. configurable: true
  22239. });
  22240. /**
  22241. * Store current camera state (fov, position, etc..)
  22242. */
  22243. Camera.prototype.storeState = function () {
  22244. this._stateStored = true;
  22245. this._storedFov = this.fov;
  22246. return this;
  22247. };
  22248. /**
  22249. * Restores the camera state values if it has been stored. You must call storeState() first
  22250. */
  22251. Camera.prototype._restoreStateValues = function () {
  22252. if (!this._stateStored) {
  22253. return false;
  22254. }
  22255. this.fov = this._storedFov;
  22256. return true;
  22257. };
  22258. /**
  22259. * Restored camera state. You must call storeState() first
  22260. */
  22261. Camera.prototype.restoreState = function () {
  22262. if (this._restoreStateValues()) {
  22263. this.onRestoreStateObservable.notifyObservers(this);
  22264. return true;
  22265. }
  22266. return false;
  22267. };
  22268. Camera.prototype.getClassName = function () {
  22269. return "Camera";
  22270. };
  22271. /**
  22272. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22273. */
  22274. Camera.prototype.toString = function (fullDetails) {
  22275. var ret = "Name: " + this.name;
  22276. ret += ", type: " + this.getClassName();
  22277. if (this.animations) {
  22278. for (var i = 0; i < this.animations.length; i++) {
  22279. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22280. }
  22281. }
  22282. if (fullDetails) {
  22283. }
  22284. return ret;
  22285. };
  22286. Object.defineProperty(Camera.prototype, "globalPosition", {
  22287. get: function () {
  22288. return this._globalPosition;
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Camera.prototype.getActiveMeshes = function () {
  22294. return this._activeMeshes;
  22295. };
  22296. Camera.prototype.isActiveMesh = function (mesh) {
  22297. return (this._activeMeshes.indexOf(mesh) !== -1);
  22298. };
  22299. /**
  22300. * Is this camera ready to be used/rendered
  22301. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22302. * @return true if the camera is ready
  22303. */
  22304. Camera.prototype.isReady = function (completeCheck) {
  22305. if (completeCheck === void 0) { completeCheck = false; }
  22306. if (completeCheck) {
  22307. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22308. var pp = _a[_i];
  22309. if (pp && !pp.isReady()) {
  22310. return false;
  22311. }
  22312. }
  22313. }
  22314. return _super.prototype.isReady.call(this, completeCheck);
  22315. };
  22316. //Cache
  22317. Camera.prototype._initCache = function () {
  22318. _super.prototype._initCache.call(this);
  22319. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22320. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22321. this._cache.mode = undefined;
  22322. this._cache.minZ = undefined;
  22323. this._cache.maxZ = undefined;
  22324. this._cache.fov = undefined;
  22325. this._cache.fovMode = undefined;
  22326. this._cache.aspectRatio = undefined;
  22327. this._cache.orthoLeft = undefined;
  22328. this._cache.orthoRight = undefined;
  22329. this._cache.orthoBottom = undefined;
  22330. this._cache.orthoTop = undefined;
  22331. this._cache.renderWidth = undefined;
  22332. this._cache.renderHeight = undefined;
  22333. };
  22334. Camera.prototype._updateCache = function (ignoreParentClass) {
  22335. if (!ignoreParentClass) {
  22336. _super.prototype._updateCache.call(this);
  22337. }
  22338. this._cache.position.copyFrom(this.position);
  22339. this._cache.upVector.copyFrom(this.upVector);
  22340. };
  22341. // Synchronized
  22342. Camera.prototype._isSynchronized = function () {
  22343. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22344. };
  22345. Camera.prototype._isSynchronizedViewMatrix = function () {
  22346. if (!_super.prototype._isSynchronized.call(this))
  22347. return false;
  22348. return this._cache.position.equals(this.position)
  22349. && this._cache.upVector.equals(this.upVector)
  22350. && this.isSynchronizedWithParent();
  22351. };
  22352. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22353. var check = this._cache.mode === this.mode
  22354. && this._cache.minZ === this.minZ
  22355. && this._cache.maxZ === this.maxZ;
  22356. if (!check) {
  22357. return false;
  22358. }
  22359. var engine = this.getEngine();
  22360. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22361. check = this._cache.fov === this.fov
  22362. && this._cache.fovMode === this.fovMode
  22363. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22364. }
  22365. else {
  22366. check = this._cache.orthoLeft === this.orthoLeft
  22367. && this._cache.orthoRight === this.orthoRight
  22368. && this._cache.orthoBottom === this.orthoBottom
  22369. && this._cache.orthoTop === this.orthoTop
  22370. && this._cache.renderWidth === engine.getRenderWidth()
  22371. && this._cache.renderHeight === engine.getRenderHeight();
  22372. }
  22373. return check;
  22374. };
  22375. // Controls
  22376. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22377. };
  22378. Camera.prototype.detachControl = function (element) {
  22379. };
  22380. Camera.prototype.update = function () {
  22381. this._checkInputs();
  22382. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22383. this._updateRigCameras();
  22384. }
  22385. };
  22386. Camera.prototype._checkInputs = function () {
  22387. this.onAfterCheckInputsObservable.notifyObservers(this);
  22388. };
  22389. Object.defineProperty(Camera.prototype, "rigCameras", {
  22390. get: function () {
  22391. return this._rigCameras;
  22392. },
  22393. enumerable: true,
  22394. configurable: true
  22395. });
  22396. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22397. get: function () {
  22398. return this._rigPostProcess;
  22399. },
  22400. enumerable: true,
  22401. configurable: true
  22402. });
  22403. /**
  22404. * Internal, gets the first post proces.
  22405. * @returns the first post process to be run on this camera.
  22406. */
  22407. Camera.prototype._getFirstPostProcess = function () {
  22408. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22409. if (this._postProcesses[ppIndex] !== null) {
  22410. return this._postProcesses[ppIndex];
  22411. }
  22412. }
  22413. return null;
  22414. };
  22415. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22416. // invalidate framebuffer
  22417. var firstPostProcess = this._getFirstPostProcess();
  22418. if (firstPostProcess) {
  22419. firstPostProcess.markTextureDirty();
  22420. }
  22421. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22422. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22423. var cam = this._rigCameras[i];
  22424. var rigPostProcess = cam._rigPostProcess;
  22425. // for VR rig, there does not have to be a post process
  22426. if (rigPostProcess) {
  22427. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22428. if (isPass) {
  22429. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22430. cam.isIntermediate = this._postProcesses.length === 0;
  22431. }
  22432. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22433. rigPostProcess.markTextureDirty();
  22434. }
  22435. else {
  22436. cam._postProcesses = this._postProcesses.slice(0);
  22437. }
  22438. }
  22439. };
  22440. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22441. if (insertAt === void 0) { insertAt = null; }
  22442. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22443. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22444. return 0;
  22445. }
  22446. if (insertAt == null || insertAt < 0) {
  22447. this._postProcesses.push(postProcess);
  22448. }
  22449. else if (this._postProcesses[insertAt] === null) {
  22450. this._postProcesses[insertAt] = postProcess;
  22451. }
  22452. else {
  22453. this._postProcesses.splice(insertAt, 0, postProcess);
  22454. }
  22455. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22456. return this._postProcesses.indexOf(postProcess);
  22457. };
  22458. Camera.prototype.detachPostProcess = function (postProcess) {
  22459. var idx = this._postProcesses.indexOf(postProcess);
  22460. if (idx !== -1) {
  22461. this._postProcesses[idx] = null;
  22462. }
  22463. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22464. };
  22465. Camera.prototype.getWorldMatrix = function () {
  22466. if (this._isSynchronizedViewMatrix()) {
  22467. return this._worldMatrix;
  22468. }
  22469. // Getting the the view matrix will also compute the world matrix.
  22470. this.getViewMatrix();
  22471. return this._worldMatrix;
  22472. };
  22473. Camera.prototype._getViewMatrix = function () {
  22474. return BABYLON.Matrix.Identity();
  22475. };
  22476. Camera.prototype.getViewMatrix = function (force) {
  22477. if (!force && this._isSynchronizedViewMatrix()) {
  22478. return this._computedViewMatrix;
  22479. }
  22480. this.updateCache();
  22481. this._computedViewMatrix = this._getViewMatrix();
  22482. this._currentRenderId = this.getScene().getRenderId();
  22483. this._childRenderId = this._currentRenderId;
  22484. this._refreshFrustumPlanes = true;
  22485. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22486. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22487. }
  22488. this.onViewMatrixChangedObservable.notifyObservers(this);
  22489. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22490. return this._computedViewMatrix;
  22491. };
  22492. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22493. this._doNotComputeProjectionMatrix = true;
  22494. if (projection !== undefined) {
  22495. this._projectionMatrix = projection;
  22496. }
  22497. };
  22498. ;
  22499. Camera.prototype.unfreezeProjectionMatrix = function () {
  22500. this._doNotComputeProjectionMatrix = false;
  22501. };
  22502. ;
  22503. Camera.prototype.getProjectionMatrix = function (force) {
  22504. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22505. return this._projectionMatrix;
  22506. }
  22507. // Cache
  22508. this._cache.mode = this.mode;
  22509. this._cache.minZ = this.minZ;
  22510. this._cache.maxZ = this.maxZ;
  22511. // Matrix
  22512. this._refreshFrustumPlanes = true;
  22513. var engine = this.getEngine();
  22514. var scene = this.getScene();
  22515. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22516. this._cache.fov = this.fov;
  22517. this._cache.fovMode = this.fovMode;
  22518. this._cache.aspectRatio = engine.getAspectRatio(this);
  22519. if (this.minZ <= 0) {
  22520. this.minZ = 0.1;
  22521. }
  22522. if (scene.useRightHandedSystem) {
  22523. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22524. }
  22525. else {
  22526. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22527. }
  22528. }
  22529. else {
  22530. var halfWidth = engine.getRenderWidth() / 2.0;
  22531. var halfHeight = engine.getRenderHeight() / 2.0;
  22532. if (scene.useRightHandedSystem) {
  22533. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22534. }
  22535. else {
  22536. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22537. }
  22538. this._cache.orthoLeft = this.orthoLeft;
  22539. this._cache.orthoRight = this.orthoRight;
  22540. this._cache.orthoBottom = this.orthoBottom;
  22541. this._cache.orthoTop = this.orthoTop;
  22542. this._cache.renderWidth = engine.getRenderWidth();
  22543. this._cache.renderHeight = engine.getRenderHeight();
  22544. }
  22545. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22546. return this._projectionMatrix;
  22547. };
  22548. Camera.prototype.getTranformationMatrix = function () {
  22549. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22550. return this._transformMatrix;
  22551. };
  22552. Camera.prototype.updateFrustumPlanes = function () {
  22553. if (!this._refreshFrustumPlanes) {
  22554. return;
  22555. }
  22556. this.getTranformationMatrix();
  22557. if (!this._frustumPlanes) {
  22558. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22559. }
  22560. else {
  22561. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22562. }
  22563. this._refreshFrustumPlanes = false;
  22564. };
  22565. Camera.prototype.isInFrustum = function (target) {
  22566. this.updateFrustumPlanes();
  22567. return target.isInFrustum(this._frustumPlanes);
  22568. };
  22569. Camera.prototype.isCompletelyInFrustum = function (target) {
  22570. this.updateFrustumPlanes();
  22571. return target.isCompletelyInFrustum(this._frustumPlanes);
  22572. };
  22573. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22574. if (length === void 0) { length = 100; }
  22575. if (!transform) {
  22576. transform = this.getWorldMatrix();
  22577. }
  22578. if (!origin) {
  22579. origin = this.position;
  22580. }
  22581. var forward = new BABYLON.Vector3(0, 0, 1);
  22582. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22583. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22584. return new BABYLON.Ray(origin, direction, length);
  22585. };
  22586. /**
  22587. * Releases resources associated with this node.
  22588. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22589. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22590. */
  22591. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22592. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22593. // Observables
  22594. this.onViewMatrixChangedObservable.clear();
  22595. this.onProjectionMatrixChangedObservable.clear();
  22596. this.onAfterCheckInputsObservable.clear();
  22597. this.onRestoreStateObservable.clear();
  22598. // Inputs
  22599. if (this.inputs) {
  22600. this.inputs.clear();
  22601. }
  22602. // Animations
  22603. this.getScene().stopAnimation(this);
  22604. // Remove from scene
  22605. this.getScene().removeCamera(this);
  22606. while (this._rigCameras.length > 0) {
  22607. var camera = this._rigCameras.pop();
  22608. if (camera) {
  22609. camera.dispose();
  22610. }
  22611. }
  22612. // Postprocesses
  22613. if (this._rigPostProcess) {
  22614. this._rigPostProcess.dispose(this);
  22615. this._rigPostProcess = null;
  22616. this._postProcesses = [];
  22617. }
  22618. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22619. this._rigPostProcess = null;
  22620. this._postProcesses = [];
  22621. }
  22622. else {
  22623. var i = this._postProcesses.length;
  22624. while (--i >= 0) {
  22625. var postProcess = this._postProcesses[i];
  22626. if (postProcess) {
  22627. postProcess.dispose(this);
  22628. }
  22629. }
  22630. }
  22631. // Render targets
  22632. var i = this.customRenderTargets.length;
  22633. while (--i >= 0) {
  22634. this.customRenderTargets[i].dispose();
  22635. }
  22636. this.customRenderTargets = [];
  22637. // Active Meshes
  22638. this._activeMeshes.dispose();
  22639. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22640. };
  22641. Object.defineProperty(Camera.prototype, "leftCamera", {
  22642. // ---- Camera rigs section ----
  22643. get: function () {
  22644. if (this._rigCameras.length < 1) {
  22645. return null;
  22646. }
  22647. return this._rigCameras[0];
  22648. },
  22649. enumerable: true,
  22650. configurable: true
  22651. });
  22652. Object.defineProperty(Camera.prototype, "rightCamera", {
  22653. get: function () {
  22654. if (this._rigCameras.length < 2) {
  22655. return null;
  22656. }
  22657. return this._rigCameras[1];
  22658. },
  22659. enumerable: true,
  22660. configurable: true
  22661. });
  22662. Camera.prototype.getLeftTarget = function () {
  22663. if (this._rigCameras.length < 1) {
  22664. return null;
  22665. }
  22666. return this._rigCameras[0].getTarget();
  22667. };
  22668. Camera.prototype.getRightTarget = function () {
  22669. if (this._rigCameras.length < 2) {
  22670. return null;
  22671. }
  22672. return this._rigCameras[1].getTarget();
  22673. };
  22674. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22675. if (this.cameraRigMode === mode) {
  22676. return;
  22677. }
  22678. while (this._rigCameras.length > 0) {
  22679. var camera = this._rigCameras.pop();
  22680. if (camera) {
  22681. camera.dispose();
  22682. }
  22683. }
  22684. this.cameraRigMode = mode;
  22685. this._cameraRigParams = {};
  22686. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22687. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22688. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22689. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22690. // create the rig cameras, unless none
  22691. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22692. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22693. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22694. if (leftCamera && rightCamera) {
  22695. this._rigCameras.push(leftCamera);
  22696. this._rigCameras.push(rightCamera);
  22697. }
  22698. }
  22699. switch (this.cameraRigMode) {
  22700. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22701. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22702. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22703. break;
  22704. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22705. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22706. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22707. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22708. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22709. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22710. break;
  22711. case Camera.RIG_MODE_VR:
  22712. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22713. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22714. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22715. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22716. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22717. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22718. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22719. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22720. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22721. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22722. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22723. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22724. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22725. if (metrics.compensateDistortion) {
  22726. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22727. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22728. }
  22729. break;
  22730. case Camera.RIG_MODE_WEBVR:
  22731. if (rigParams.vrDisplay) {
  22732. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22733. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22734. //Left eye
  22735. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22736. this._rigCameras[0].setCameraRigParameter("left", true);
  22737. //leaving this for future reference
  22738. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22739. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22740. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22741. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22742. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22743. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22744. this._rigCameras[0].parent = this;
  22745. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22746. //Right eye
  22747. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22748. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22749. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22750. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22751. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22752. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22753. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22754. this._rigCameras[1].parent = this;
  22755. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22756. if (Camera.UseAlternateWebVRRendering) {
  22757. this._rigCameras[1]._skipRendering = true;
  22758. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22759. }
  22760. }
  22761. break;
  22762. }
  22763. this._cascadePostProcessesToRigCams();
  22764. this.update();
  22765. };
  22766. Camera.prototype._getVRProjectionMatrix = function () {
  22767. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22768. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22769. return this._projectionMatrix;
  22770. };
  22771. Camera.prototype._updateCameraRotationMatrix = function () {
  22772. //Here for WebVR
  22773. };
  22774. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22775. //Here for WebVR
  22776. };
  22777. /**
  22778. * This function MUST be overwritten by the different WebVR cameras available.
  22779. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22780. */
  22781. Camera.prototype._getWebVRProjectionMatrix = function () {
  22782. return BABYLON.Matrix.Identity();
  22783. };
  22784. /**
  22785. * This function MUST be overwritten by the different WebVR cameras available.
  22786. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22787. */
  22788. Camera.prototype._getWebVRViewMatrix = function () {
  22789. return BABYLON.Matrix.Identity();
  22790. };
  22791. Camera.prototype.setCameraRigParameter = function (name, value) {
  22792. if (!this._cameraRigParams) {
  22793. this._cameraRigParams = {};
  22794. }
  22795. this._cameraRigParams[name] = value;
  22796. //provisionnally:
  22797. if (name === "interaxialDistance") {
  22798. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22799. }
  22800. };
  22801. /**
  22802. * needs to be overridden by children so sub has required properties to be copied
  22803. */
  22804. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22805. return null;
  22806. };
  22807. /**
  22808. * May need to be overridden by children
  22809. */
  22810. Camera.prototype._updateRigCameras = function () {
  22811. for (var i = 0; i < this._rigCameras.length; i++) {
  22812. this._rigCameras[i].minZ = this.minZ;
  22813. this._rigCameras[i].maxZ = this.maxZ;
  22814. this._rigCameras[i].fov = this.fov;
  22815. }
  22816. // only update viewport when ANAGLYPH
  22817. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22818. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22819. }
  22820. };
  22821. Camera.prototype._setupInputs = function () {
  22822. };
  22823. Camera.prototype.serialize = function () {
  22824. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22825. // Type
  22826. serializationObject.type = this.getClassName();
  22827. // Parent
  22828. if (this.parent) {
  22829. serializationObject.parentId = this.parent.id;
  22830. }
  22831. if (this.inputs) {
  22832. this.inputs.serialize(serializationObject);
  22833. }
  22834. // Animations
  22835. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22836. serializationObject.ranges = this.serializeAnimationRanges();
  22837. return serializationObject;
  22838. };
  22839. Camera.prototype.clone = function (name) {
  22840. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22841. };
  22842. Camera.prototype.getDirection = function (localAxis) {
  22843. var result = BABYLON.Vector3.Zero();
  22844. this.getDirectionToRef(localAxis, result);
  22845. return result;
  22846. };
  22847. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22848. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22849. };
  22850. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22851. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22852. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22853. switch (type) {
  22854. case "ArcRotateCamera":
  22855. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22856. case "DeviceOrientationCamera":
  22857. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22858. case "FollowCamera":
  22859. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22860. case "ArcFollowCamera":
  22861. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22862. case "GamepadCamera":
  22863. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22864. case "TouchCamera":
  22865. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22866. case "VirtualJoysticksCamera":
  22867. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22868. case "WebVRFreeCamera":
  22869. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22870. case "WebVRGamepadCamera":
  22871. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22872. case "VRDeviceOrientationFreeCamera":
  22873. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22874. case "VRDeviceOrientationGamepadCamera":
  22875. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22876. case "AnaglyphArcRotateCamera":
  22877. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22878. case "AnaglyphFreeCamera":
  22879. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22880. case "AnaglyphGamepadCamera":
  22881. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22882. case "AnaglyphUniversalCamera":
  22883. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22884. case "StereoscopicArcRotateCamera":
  22885. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22886. case "StereoscopicFreeCamera":
  22887. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22888. case "StereoscopicGamepadCamera":
  22889. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22890. case "StereoscopicUniversalCamera":
  22891. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22892. case "FreeCamera": // Forcing Universal here
  22893. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22894. default: // Universal Camera is the default value
  22895. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22896. }
  22897. };
  22898. Camera.prototype.computeWorldMatrix = function () {
  22899. return this.getWorldMatrix();
  22900. };
  22901. Camera.Parse = function (parsedCamera, scene) {
  22902. var type = parsedCamera.type;
  22903. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22904. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22905. // Parent
  22906. if (parsedCamera.parentId) {
  22907. camera._waitingParentId = parsedCamera.parentId;
  22908. }
  22909. //If camera has an input manager, let it parse inputs settings
  22910. if (camera.inputs) {
  22911. camera.inputs.parse(parsedCamera);
  22912. camera._setupInputs();
  22913. }
  22914. if (camera.setPosition) { // need to force position
  22915. camera.position.copyFromFloats(0, 0, 0);
  22916. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22917. }
  22918. // Target
  22919. if (parsedCamera.target) {
  22920. if (camera.setTarget) {
  22921. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22922. }
  22923. }
  22924. // Apply 3d rig, when found
  22925. if (parsedCamera.cameraRigMode) {
  22926. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22927. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22928. }
  22929. // Animations
  22930. if (parsedCamera.animations) {
  22931. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22932. var parsedAnimation = parsedCamera.animations[animationIndex];
  22933. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22934. }
  22935. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22936. }
  22937. if (parsedCamera.autoAnimate) {
  22938. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22939. }
  22940. return camera;
  22941. };
  22942. // Statics
  22943. Camera._PERSPECTIVE_CAMERA = 0;
  22944. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22945. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22946. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22947. Camera._RIG_MODE_NONE = 0;
  22948. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22949. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22950. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22951. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22952. Camera._RIG_MODE_VR = 20;
  22953. Camera._RIG_MODE_WEBVR = 21;
  22954. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22955. Camera.UseAlternateWebVRRendering = false;
  22956. __decorate([
  22957. BABYLON.serializeAsVector3()
  22958. ], Camera.prototype, "position", void 0);
  22959. __decorate([
  22960. BABYLON.serializeAsVector3()
  22961. ], Camera.prototype, "upVector", void 0);
  22962. __decorate([
  22963. BABYLON.serialize()
  22964. ], Camera.prototype, "orthoLeft", void 0);
  22965. __decorate([
  22966. BABYLON.serialize()
  22967. ], Camera.prototype, "orthoRight", void 0);
  22968. __decorate([
  22969. BABYLON.serialize()
  22970. ], Camera.prototype, "orthoBottom", void 0);
  22971. __decorate([
  22972. BABYLON.serialize()
  22973. ], Camera.prototype, "orthoTop", void 0);
  22974. __decorate([
  22975. BABYLON.serialize()
  22976. ], Camera.prototype, "fov", void 0);
  22977. __decorate([
  22978. BABYLON.serialize()
  22979. ], Camera.prototype, "minZ", void 0);
  22980. __decorate([
  22981. BABYLON.serialize()
  22982. ], Camera.prototype, "maxZ", void 0);
  22983. __decorate([
  22984. BABYLON.serialize()
  22985. ], Camera.prototype, "inertia", void 0);
  22986. __decorate([
  22987. BABYLON.serialize()
  22988. ], Camera.prototype, "mode", void 0);
  22989. __decorate([
  22990. BABYLON.serialize()
  22991. ], Camera.prototype, "layerMask", void 0);
  22992. __decorate([
  22993. BABYLON.serialize()
  22994. ], Camera.prototype, "fovMode", void 0);
  22995. __decorate([
  22996. BABYLON.serialize()
  22997. ], Camera.prototype, "cameraRigMode", void 0);
  22998. __decorate([
  22999. BABYLON.serialize()
  23000. ], Camera.prototype, "interaxialDistance", void 0);
  23001. __decorate([
  23002. BABYLON.serialize()
  23003. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23004. return Camera;
  23005. }(BABYLON.Node));
  23006. BABYLON.Camera = Camera;
  23007. })(BABYLON || (BABYLON = {}));
  23008. //# sourceMappingURL=babylon.camera.js.map
  23009. var BABYLON;
  23010. (function (BABYLON) {
  23011. var RenderingManager = /** @class */ (function () {
  23012. function RenderingManager(scene) {
  23013. this._renderingGroups = new Array();
  23014. this._autoClearDepthStencil = {};
  23015. this._customOpaqueSortCompareFn = {};
  23016. this._customAlphaTestSortCompareFn = {};
  23017. this._customTransparentSortCompareFn = {};
  23018. this._renderinGroupInfo = null;
  23019. this._scene = scene;
  23020. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23021. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23022. }
  23023. }
  23024. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23025. if (depth === void 0) { depth = true; }
  23026. if (stencil === void 0) { stencil = true; }
  23027. if (this._depthStencilBufferAlreadyCleaned) {
  23028. return;
  23029. }
  23030. this._scene.getEngine().clear(null, false, depth, stencil);
  23031. this._depthStencilBufferAlreadyCleaned = true;
  23032. };
  23033. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23034. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23035. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23036. var info = null;
  23037. if (observable) {
  23038. if (!this._renderinGroupInfo) {
  23039. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23040. }
  23041. info = this._renderinGroupInfo;
  23042. info.scene = this._scene;
  23043. info.camera = this._scene.activeCamera;
  23044. }
  23045. // Dispatch sprites
  23046. if (renderSprites) {
  23047. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23048. var manager = this._scene.spriteManagers[index];
  23049. this.dispatchSprites(manager);
  23050. }
  23051. }
  23052. // Render
  23053. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23054. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23055. var renderingGroup = this._renderingGroups[index];
  23056. if (!renderingGroup && !observable)
  23057. continue;
  23058. var renderingGroupMask = 0;
  23059. // Fire PRECLEAR stage
  23060. if (observable && info) {
  23061. renderingGroupMask = Math.pow(2, index);
  23062. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23063. info.renderingGroupId = index;
  23064. observable.notifyObservers(info, renderingGroupMask);
  23065. }
  23066. // Clear depth/stencil if needed
  23067. if (RenderingManager.AUTOCLEAR) {
  23068. var autoClear = this._autoClearDepthStencil[index];
  23069. if (autoClear && autoClear.autoClear) {
  23070. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23071. }
  23072. }
  23073. if (observable && info) {
  23074. // Fire PREOPAQUE stage
  23075. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23076. observable.notifyObservers(info, renderingGroupMask);
  23077. // Fire PRETRANSPARENT stage
  23078. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23079. observable.notifyObservers(info, renderingGroupMask);
  23080. }
  23081. if (renderingGroup)
  23082. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23083. // Fire POSTTRANSPARENT stage
  23084. if (observable && info) {
  23085. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23086. observable.notifyObservers(info, renderingGroupMask);
  23087. }
  23088. }
  23089. };
  23090. RenderingManager.prototype.reset = function () {
  23091. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23092. var renderingGroup = this._renderingGroups[index];
  23093. if (renderingGroup) {
  23094. renderingGroup.prepare();
  23095. }
  23096. }
  23097. };
  23098. RenderingManager.prototype.dispose = function () {
  23099. this.freeRenderingGroups();
  23100. this._renderingGroups.length = 0;
  23101. };
  23102. /**
  23103. * Clear the info related to rendering groups preventing retention points during dispose.
  23104. */
  23105. RenderingManager.prototype.freeRenderingGroups = function () {
  23106. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23107. var renderingGroup = this._renderingGroups[index];
  23108. if (renderingGroup) {
  23109. renderingGroup.dispose();
  23110. }
  23111. }
  23112. };
  23113. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23114. if (this._renderingGroups[renderingGroupId] === undefined) {
  23115. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23116. }
  23117. };
  23118. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23119. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23120. this._prepareRenderingGroup(renderingGroupId);
  23121. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23122. };
  23123. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23124. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23125. this._prepareRenderingGroup(renderingGroupId);
  23126. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23127. };
  23128. /**
  23129. * @param subMesh The submesh to dispatch
  23130. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23131. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23132. */
  23133. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23134. if (mesh === undefined) {
  23135. mesh = subMesh.getMesh();
  23136. }
  23137. var renderingGroupId = mesh.renderingGroupId || 0;
  23138. this._prepareRenderingGroup(renderingGroupId);
  23139. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23140. };
  23141. /**
  23142. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23143. * This allowed control for front to back rendering or reversly depending of the special needs.
  23144. *
  23145. * @param renderingGroupId The rendering group id corresponding to its index
  23146. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23147. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23148. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23149. */
  23150. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23151. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23152. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23153. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23154. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23155. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23156. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23157. if (this._renderingGroups[renderingGroupId]) {
  23158. var group = this._renderingGroups[renderingGroupId];
  23159. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23160. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23161. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23162. }
  23163. };
  23164. /**
  23165. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23166. *
  23167. * @param renderingGroupId The rendering group id corresponding to its index
  23168. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23169. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23170. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23171. */
  23172. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23173. if (depth === void 0) { depth = true; }
  23174. if (stencil === void 0) { stencil = true; }
  23175. this._autoClearDepthStencil[renderingGroupId] = {
  23176. autoClear: autoClearDepthStencil,
  23177. depth: depth,
  23178. stencil: stencil
  23179. };
  23180. };
  23181. /**
  23182. * The max id used for rendering groups (not included)
  23183. */
  23184. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23185. /**
  23186. * The min id used for rendering groups (included)
  23187. */
  23188. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23189. /**
  23190. * Used to globally prevent autoclearing scenes.
  23191. */
  23192. RenderingManager.AUTOCLEAR = true;
  23193. return RenderingManager;
  23194. }());
  23195. BABYLON.RenderingManager = RenderingManager;
  23196. })(BABYLON || (BABYLON = {}));
  23197. //# sourceMappingURL=babylon.renderingManager.js.map
  23198. var BABYLON;
  23199. (function (BABYLON) {
  23200. var RenderingGroup = /** @class */ (function () {
  23201. /**
  23202. * Creates a new rendering group.
  23203. * @param index The rendering group index
  23204. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23205. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23206. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23207. */
  23208. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23209. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23210. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23211. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23212. this.index = index;
  23213. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23214. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23215. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23216. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23217. this._particleSystems = new BABYLON.SmartArray(256);
  23218. this._spriteManagers = new BABYLON.SmartArray(256);
  23219. this._edgesRenderers = new BABYLON.SmartArray(16);
  23220. this._scene = scene;
  23221. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23222. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23223. this.transparentSortCompareFn = transparentSortCompareFn;
  23224. }
  23225. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23226. /**
  23227. * Set the opaque sort comparison function.
  23228. * If null the sub meshes will be render in the order they were created
  23229. */
  23230. set: function (value) {
  23231. this._opaqueSortCompareFn = value;
  23232. if (value) {
  23233. this._renderOpaque = this.renderOpaqueSorted;
  23234. }
  23235. else {
  23236. this._renderOpaque = RenderingGroup.renderUnsorted;
  23237. }
  23238. },
  23239. enumerable: true,
  23240. configurable: true
  23241. });
  23242. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23243. /**
  23244. * Set the alpha test sort comparison function.
  23245. * If null the sub meshes will be render in the order they were created
  23246. */
  23247. set: function (value) {
  23248. this._alphaTestSortCompareFn = value;
  23249. if (value) {
  23250. this._renderAlphaTest = this.renderAlphaTestSorted;
  23251. }
  23252. else {
  23253. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23254. }
  23255. },
  23256. enumerable: true,
  23257. configurable: true
  23258. });
  23259. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23260. /**
  23261. * Set the transparent sort comparison function.
  23262. * If null the sub meshes will be render in the order they were created
  23263. */
  23264. set: function (value) {
  23265. if (value) {
  23266. this._transparentSortCompareFn = value;
  23267. }
  23268. else {
  23269. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23270. }
  23271. this._renderTransparent = this.renderTransparentSorted;
  23272. },
  23273. enumerable: true,
  23274. configurable: true
  23275. });
  23276. /**
  23277. * Render all the sub meshes contained in the group.
  23278. * @param customRenderFunction Used to override the default render behaviour of the group.
  23279. * @returns true if rendered some submeshes.
  23280. */
  23281. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23282. if (customRenderFunction) {
  23283. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23284. return;
  23285. }
  23286. var engine = this._scene.getEngine();
  23287. // Depth only
  23288. if (this._depthOnlySubMeshes.length !== 0) {
  23289. engine.setColorWrite(false);
  23290. this._renderAlphaTest(this._depthOnlySubMeshes);
  23291. engine.setColorWrite(true);
  23292. }
  23293. // Opaque
  23294. if (this._opaqueSubMeshes.length !== 0) {
  23295. this._renderOpaque(this._opaqueSubMeshes);
  23296. }
  23297. // Alpha test
  23298. if (this._alphaTestSubMeshes.length !== 0) {
  23299. this._renderAlphaTest(this._alphaTestSubMeshes);
  23300. }
  23301. var stencilState = engine.getStencilBuffer();
  23302. engine.setStencilBuffer(false);
  23303. // Sprites
  23304. if (renderSprites) {
  23305. this._renderSprites();
  23306. }
  23307. // Particles
  23308. if (renderParticles) {
  23309. this._renderParticles(activeMeshes);
  23310. }
  23311. if (this.onBeforeTransparentRendering) {
  23312. this.onBeforeTransparentRendering();
  23313. }
  23314. // Transparent
  23315. if (this._transparentSubMeshes.length !== 0) {
  23316. this._renderTransparent(this._transparentSubMeshes);
  23317. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23318. }
  23319. // Set back stencil to false in case it changes before the edge renderer.
  23320. engine.setStencilBuffer(false);
  23321. // Edges
  23322. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23323. this._edgesRenderers.data[edgesRendererIndex].render();
  23324. }
  23325. // Restore Stencil state.
  23326. engine.setStencilBuffer(stencilState);
  23327. };
  23328. /**
  23329. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23330. * @param subMeshes The submeshes to render
  23331. */
  23332. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23333. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23334. };
  23335. /**
  23336. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23337. * @param subMeshes The submeshes to render
  23338. */
  23339. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23340. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23341. };
  23342. /**
  23343. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23344. * @param subMeshes The submeshes to render
  23345. */
  23346. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23347. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23348. };
  23349. /**
  23350. * Renders the submeshes in a specified order.
  23351. * @param subMeshes The submeshes to sort before render
  23352. * @param sortCompareFn The comparison function use to sort
  23353. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23354. * @param transparent Specifies to activate blending if true
  23355. */
  23356. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23357. var subIndex = 0;
  23358. var subMesh;
  23359. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23360. for (; subIndex < subMeshes.length; subIndex++) {
  23361. subMesh = subMeshes.data[subIndex];
  23362. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23363. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23364. }
  23365. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23366. if (sortCompareFn) {
  23367. sortedArray.sort(sortCompareFn);
  23368. }
  23369. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23370. subMesh = sortedArray[subIndex];
  23371. if (transparent) {
  23372. var material = subMesh.getMaterial();
  23373. if (material && material.needDepthPrePass) {
  23374. var engine = material.getScene().getEngine();
  23375. engine.setColorWrite(false);
  23376. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23377. subMesh.render(false);
  23378. engine.setColorWrite(true);
  23379. }
  23380. }
  23381. subMesh.render(transparent);
  23382. }
  23383. };
  23384. /**
  23385. * Renders the submeshes in the order they were dispatched (no sort applied).
  23386. * @param subMeshes The submeshes to render
  23387. */
  23388. RenderingGroup.renderUnsorted = function (subMeshes) {
  23389. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23390. var submesh = subMeshes.data[subIndex];
  23391. submesh.render(false);
  23392. }
  23393. };
  23394. /**
  23395. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23396. * are rendered back to front if in the same alpha index.
  23397. *
  23398. * @param a The first submesh
  23399. * @param b The second submesh
  23400. * @returns The result of the comparison
  23401. */
  23402. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23403. // Alpha index first
  23404. if (a._alphaIndex > b._alphaIndex) {
  23405. return 1;
  23406. }
  23407. if (a._alphaIndex < b._alphaIndex) {
  23408. return -1;
  23409. }
  23410. // Then distance to camera
  23411. return RenderingGroup.backToFrontSortCompare(a, b);
  23412. };
  23413. /**
  23414. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23415. * are rendered back to front.
  23416. *
  23417. * @param a The first submesh
  23418. * @param b The second submesh
  23419. * @returns The result of the comparison
  23420. */
  23421. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23422. // Then distance to camera
  23423. if (a._distanceToCamera < b._distanceToCamera) {
  23424. return 1;
  23425. }
  23426. if (a._distanceToCamera > b._distanceToCamera) {
  23427. return -1;
  23428. }
  23429. return 0;
  23430. };
  23431. /**
  23432. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23433. * are rendered front to back (prevent overdraw).
  23434. *
  23435. * @param a The first submesh
  23436. * @param b The second submesh
  23437. * @returns The result of the comparison
  23438. */
  23439. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23440. // Then distance to camera
  23441. if (a._distanceToCamera < b._distanceToCamera) {
  23442. return -1;
  23443. }
  23444. if (a._distanceToCamera > b._distanceToCamera) {
  23445. return 1;
  23446. }
  23447. return 0;
  23448. };
  23449. /**
  23450. * Resets the different lists of submeshes to prepare a new frame.
  23451. */
  23452. RenderingGroup.prototype.prepare = function () {
  23453. this._opaqueSubMeshes.reset();
  23454. this._transparentSubMeshes.reset();
  23455. this._alphaTestSubMeshes.reset();
  23456. this._depthOnlySubMeshes.reset();
  23457. this._particleSystems.reset();
  23458. this._spriteManagers.reset();
  23459. this._edgesRenderers.reset();
  23460. };
  23461. RenderingGroup.prototype.dispose = function () {
  23462. this._opaqueSubMeshes.dispose();
  23463. this._transparentSubMeshes.dispose();
  23464. this._alphaTestSubMeshes.dispose();
  23465. this._depthOnlySubMeshes.dispose();
  23466. this._particleSystems.dispose();
  23467. this._spriteManagers.dispose();
  23468. this._edgesRenderers.dispose();
  23469. };
  23470. /**
  23471. * Inserts the submesh in its correct queue depending on its material.
  23472. * @param subMesh The submesh to dispatch
  23473. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23474. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23475. */
  23476. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23477. // Get mesh and materials if not provided
  23478. if (mesh === undefined) {
  23479. mesh = subMesh.getMesh();
  23480. }
  23481. if (material === undefined) {
  23482. material = subMesh.getMaterial();
  23483. }
  23484. if (material === null || material === undefined) {
  23485. return;
  23486. }
  23487. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23488. this._transparentSubMeshes.push(subMesh);
  23489. }
  23490. else if (material.needAlphaTesting()) { // Alpha test
  23491. if (material.needDepthPrePass) {
  23492. this._depthOnlySubMeshes.push(subMesh);
  23493. }
  23494. this._alphaTestSubMeshes.push(subMesh);
  23495. }
  23496. else {
  23497. if (material.needDepthPrePass) {
  23498. this._depthOnlySubMeshes.push(subMesh);
  23499. }
  23500. this._opaqueSubMeshes.push(subMesh); // Opaque
  23501. }
  23502. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23503. this._edgesRenderers.push(mesh._edgesRenderer);
  23504. }
  23505. };
  23506. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23507. this._spriteManagers.push(spriteManager);
  23508. };
  23509. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23510. this._particleSystems.push(particleSystem);
  23511. };
  23512. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23513. if (this._particleSystems.length === 0) {
  23514. return;
  23515. }
  23516. // Particles
  23517. var activeCamera = this._scene.activeCamera;
  23518. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23519. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23520. var particleSystem = this._particleSystems.data[particleIndex];
  23521. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23522. continue;
  23523. }
  23524. var emitter = particleSystem.emitter;
  23525. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23526. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23527. }
  23528. }
  23529. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23530. };
  23531. RenderingGroup.prototype._renderSprites = function () {
  23532. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23533. return;
  23534. }
  23535. // Sprites
  23536. var activeCamera = this._scene.activeCamera;
  23537. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23538. for (var id = 0; id < this._spriteManagers.length; id++) {
  23539. var spriteManager = this._spriteManagers.data[id];
  23540. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23541. spriteManager.render();
  23542. }
  23543. }
  23544. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23545. };
  23546. return RenderingGroup;
  23547. }());
  23548. BABYLON.RenderingGroup = RenderingGroup;
  23549. })(BABYLON || (BABYLON = {}));
  23550. //# sourceMappingURL=babylon.renderingGroup.js.map
  23551. var BABYLON;
  23552. (function (BABYLON) {
  23553. /** @hidden */
  23554. var ClickInfo = /** @class */ (function () {
  23555. function ClickInfo() {
  23556. this._singleClick = false;
  23557. this._doubleClick = false;
  23558. this._hasSwiped = false;
  23559. this._ignore = false;
  23560. }
  23561. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23562. get: function () {
  23563. return this._singleClick;
  23564. },
  23565. set: function (b) {
  23566. this._singleClick = b;
  23567. },
  23568. enumerable: true,
  23569. configurable: true
  23570. });
  23571. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23572. get: function () {
  23573. return this._doubleClick;
  23574. },
  23575. set: function (b) {
  23576. this._doubleClick = b;
  23577. },
  23578. enumerable: true,
  23579. configurable: true
  23580. });
  23581. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23582. get: function () {
  23583. return this._hasSwiped;
  23584. },
  23585. set: function (b) {
  23586. this._hasSwiped = b;
  23587. },
  23588. enumerable: true,
  23589. configurable: true
  23590. });
  23591. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23592. get: function () {
  23593. return this._ignore;
  23594. },
  23595. set: function (b) {
  23596. this._ignore = b;
  23597. },
  23598. enumerable: true,
  23599. configurable: true
  23600. });
  23601. return ClickInfo;
  23602. }());
  23603. /**
  23604. * This class is used by the onRenderingGroupObservable
  23605. */
  23606. var RenderingGroupInfo = /** @class */ (function () {
  23607. function RenderingGroupInfo() {
  23608. }
  23609. /**
  23610. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23611. * This stage will be fired no matter what
  23612. */
  23613. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23614. /**
  23615. * Called before opaque object are rendered.
  23616. * This stage will be fired only if there's 3D Opaque content to render
  23617. */
  23618. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23619. /**
  23620. * Called after the opaque objects are rendered and before the transparent ones
  23621. * This stage will be fired only if there's 3D transparent content to render
  23622. */
  23623. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23624. /**
  23625. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23626. * This stage will be fired no matter what
  23627. */
  23628. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23629. return RenderingGroupInfo;
  23630. }());
  23631. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23632. /**
  23633. * Represents a scene to be rendered by the engine.
  23634. * @see http://doc.babylonjs.com/features/scene
  23635. */
  23636. var Scene = /** @class */ (function () {
  23637. /**
  23638. * Creates a new Scene
  23639. * @param engine defines the engine to use to render this scene
  23640. */
  23641. function Scene(engine) {
  23642. // Members
  23643. /**
  23644. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23645. */
  23646. this.autoClear = true;
  23647. /**
  23648. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23649. */
  23650. this.autoClearDepthAndStencil = true;
  23651. /**
  23652. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23653. */
  23654. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23655. /**
  23656. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23657. */
  23658. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23659. this._forceWireframe = false;
  23660. this._forcePointsCloud = false;
  23661. /**
  23662. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23663. */
  23664. this.forceShowBoundingBoxes = false;
  23665. /**
  23666. * Gets or sets a boolean indicating if animations are enabled
  23667. */
  23668. this.animationsEnabled = true;
  23669. this._animationPropertiesOverride = null;
  23670. /**
  23671. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23672. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23673. */
  23674. this.useConstantAnimationDeltaTime = false;
  23675. /**
  23676. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23677. * Please note that it requires to run a ray cast through the scene on every frame
  23678. */
  23679. this.constantlyUpdateMeshUnderPointer = false;
  23680. /**
  23681. * Defines the HTML cursor to use when hovering over interactive elements
  23682. */
  23683. this.hoverCursor = "pointer";
  23684. /**
  23685. * Defines the HTML default cursor to use (empty by default)
  23686. */
  23687. this.defaultCursor = "";
  23688. /**
  23689. * This is used to call preventDefault() on pointer down
  23690. * in order to block unwanted artifacts like system double clicks
  23691. */
  23692. this.preventDefaultOnPointerDown = true;
  23693. // Metadata
  23694. /**
  23695. * Gets or sets user defined metadata
  23696. */
  23697. this.metadata = null;
  23698. /**
  23699. * Use this array to add regular expressions used to disable offline support for specific urls
  23700. */
  23701. this.disableOfflineSupportExceptionRules = new Array();
  23702. /**
  23703. * An event triggered when the scene is disposed.
  23704. */
  23705. this.onDisposeObservable = new BABYLON.Observable();
  23706. this._onDisposeObserver = null;
  23707. /**
  23708. * An event triggered before rendering the scene (right after animations and physics)
  23709. */
  23710. this.onBeforeRenderObservable = new BABYLON.Observable();
  23711. this._onBeforeRenderObserver = null;
  23712. /**
  23713. * An event triggered after rendering the scene
  23714. */
  23715. this.onAfterRenderObservable = new BABYLON.Observable();
  23716. this._onAfterRenderObserver = null;
  23717. /**
  23718. * An event triggered before animating the scene
  23719. */
  23720. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23721. /**
  23722. * An event triggered after animations processing
  23723. */
  23724. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23725. /**
  23726. * An event triggered before draw calls are ready to be sent
  23727. */
  23728. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23729. /**
  23730. * An event triggered after draw calls have been sent
  23731. */
  23732. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23733. /**
  23734. * An event triggered when physic simulation is about to be run
  23735. */
  23736. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23737. /**
  23738. * An event triggered when physic simulation has been done
  23739. */
  23740. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23741. /**
  23742. * An event triggered when the scene is ready
  23743. */
  23744. this.onReadyObservable = new BABYLON.Observable();
  23745. /**
  23746. * An event triggered before rendering a camera
  23747. */
  23748. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23749. this._onBeforeCameraRenderObserver = null;
  23750. /**
  23751. * An event triggered after rendering a camera
  23752. */
  23753. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23754. this._onAfterCameraRenderObserver = null;
  23755. /**
  23756. * An event triggered when active meshes evaluation is about to start
  23757. */
  23758. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23759. /**
  23760. * An event triggered when active meshes evaluation is done
  23761. */
  23762. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23763. /**
  23764. * An event triggered when particles rendering is about to start
  23765. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23766. */
  23767. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23768. /**
  23769. * An event triggered when particles rendering is done
  23770. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23771. */
  23772. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23773. /**
  23774. * An event triggered when sprites rendering is about to start
  23775. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23776. */
  23777. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23778. /**
  23779. * An event triggered when sprites rendering is done
  23780. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23781. */
  23782. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23783. /**
  23784. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23785. */
  23786. this.onDataLoadedObservable = new BABYLON.Observable();
  23787. /**
  23788. * An event triggered when a camera is created
  23789. */
  23790. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23791. /**
  23792. * An event triggered when a camera is removed
  23793. */
  23794. this.onCameraRemovedObservable = new BABYLON.Observable();
  23795. /**
  23796. * An event triggered when a light is created
  23797. */
  23798. this.onNewLightAddedObservable = new BABYLON.Observable();
  23799. /**
  23800. * An event triggered when a light is removed
  23801. */
  23802. this.onLightRemovedObservable = new BABYLON.Observable();
  23803. /**
  23804. * An event triggered when a geometry is created
  23805. */
  23806. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23807. /**
  23808. * An event triggered when a geometry is removed
  23809. */
  23810. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23811. /**
  23812. * An event triggered when a transform node is created
  23813. */
  23814. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23815. /**
  23816. * An event triggered when a transform node is removed
  23817. */
  23818. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23819. /**
  23820. * An event triggered when a mesh is created
  23821. */
  23822. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23823. /**
  23824. * An event triggered when a mesh is removed
  23825. */
  23826. this.onMeshRemovedObservable = new BABYLON.Observable();
  23827. /**
  23828. * An event triggered when render targets are about to be rendered
  23829. * Can happen multiple times per frame.
  23830. */
  23831. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23832. /**
  23833. * An event triggered when render targets were rendered.
  23834. * Can happen multiple times per frame.
  23835. */
  23836. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23837. /**
  23838. * An event triggered before calculating deterministic simulation step
  23839. */
  23840. this.onBeforeStepObservable = new BABYLON.Observable();
  23841. /**
  23842. * An event triggered after calculating deterministic simulation step
  23843. */
  23844. this.onAfterStepObservable = new BABYLON.Observable();
  23845. /**
  23846. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23847. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23848. * 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)
  23849. */
  23850. this.onRenderingGroupObservable = new BABYLON.Observable();
  23851. // Animations
  23852. /**
  23853. * Gets a list of Animations associated with the scene
  23854. */
  23855. this.animations = [];
  23856. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23857. /**
  23858. * 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).
  23859. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23860. */
  23861. this.onPrePointerObservable = new BABYLON.Observable();
  23862. /**
  23863. * Observable event triggered each time an input event is received from the rendering canvas
  23864. */
  23865. this.onPointerObservable = new BABYLON.Observable();
  23866. this._meshPickProceed = false;
  23867. this._currentPickResult = null;
  23868. this._previousPickResult = null;
  23869. this._totalPointersPressed = 0;
  23870. this._doubleClickOccured = false;
  23871. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23872. this.cameraToUseForPointers = null;
  23873. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23874. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23875. this._startingPointerTime = 0;
  23876. this._previousStartingPointerTime = 0;
  23877. this._pointerCaptures = {};
  23878. // Deterministic lockstep
  23879. this._timeAccumulator = 0;
  23880. this._currentStepId = 0;
  23881. this._currentInternalStep = 0;
  23882. // Keyboard
  23883. /**
  23884. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23885. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23886. */
  23887. this.onPreKeyboardObservable = new BABYLON.Observable();
  23888. /**
  23889. * Observable event triggered each time an keyboard event is received from the hosting window
  23890. */
  23891. this.onKeyboardObservable = new BABYLON.Observable();
  23892. // Coordinates system
  23893. this._useRightHandedSystem = false;
  23894. // Fog
  23895. this._fogEnabled = true;
  23896. this._fogMode = Scene.FOGMODE_NONE;
  23897. /**
  23898. * Gets or sets the fog color to use
  23899. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23900. */
  23901. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23902. /**
  23903. * Gets or sets the fog density to use
  23904. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23905. */
  23906. this.fogDensity = 0.1;
  23907. /**
  23908. * Gets or sets the fog start distance to use
  23909. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23910. */
  23911. this.fogStart = 0;
  23912. /**
  23913. * Gets or sets the fog end distance to use
  23914. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23915. */
  23916. this.fogEnd = 1000.0;
  23917. // Lights
  23918. this._shadowsEnabled = true;
  23919. this._lightsEnabled = true;
  23920. /**
  23921. * All of the lights added to this scene
  23922. * @see http://doc.babylonjs.com/babylon101/lights
  23923. */
  23924. this.lights = new Array();
  23925. // Cameras
  23926. /** All of the cameras added to this scene.
  23927. * @see http://doc.babylonjs.com/babylon101/cameras
  23928. */
  23929. this.cameras = new Array();
  23930. /** All of the active cameras added to this scene. */
  23931. this.activeCameras = new Array();
  23932. // Meshes
  23933. /**
  23934. * All of the tranform nodes added to this scene
  23935. * @see http://doc.babylonjs.com/how_to/transformnode
  23936. */
  23937. this.transformNodes = new Array();
  23938. /**
  23939. * All of the (abstract) meshes added to this scene
  23940. */
  23941. this.meshes = new Array();
  23942. /**
  23943. * All of the animation groups added to this scene
  23944. * @see http://doc.babylonjs.com/how_to/group
  23945. */
  23946. this.animationGroups = new Array();
  23947. // Geometries
  23948. this._geometries = new Array();
  23949. /**
  23950. * All of the materials added to this scene
  23951. * @see http://doc.babylonjs.com/babylon101/materials
  23952. */
  23953. this.materials = new Array();
  23954. /**
  23955. * All of the multi-materials added to this scene
  23956. * @see http://doc.babylonjs.com/how_to/multi_materials
  23957. */
  23958. this.multiMaterials = new Array();
  23959. // Textures
  23960. this._texturesEnabled = true;
  23961. /**
  23962. * All of the textures added to this scene
  23963. */
  23964. this.textures = new Array();
  23965. // Particles
  23966. /**
  23967. * Gets or sets a boolean indicating if particles are enabled on this scene
  23968. */
  23969. this.particlesEnabled = true;
  23970. /**
  23971. * All of the particle systems added to this scene
  23972. * @see http://doc.babylonjs.com/babylon101/particles
  23973. */
  23974. this.particleSystems = new Array();
  23975. // Sprites
  23976. /**
  23977. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23978. */
  23979. this.spritesEnabled = true;
  23980. /**
  23981. * All of the sprite managers added to this scene
  23982. * @see http://doc.babylonjs.com/babylon101/sprites
  23983. */
  23984. this.spriteManagers = new Array();
  23985. /**
  23986. * The list of layers (background and foreground) of the scene
  23987. */
  23988. this.layers = new Array();
  23989. /**
  23990. * The list of effect layers (highlights/glow) added to the scene
  23991. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23992. * @see http://doc.babylonjs.com/how_to/glow_layer
  23993. */
  23994. this.effectLayers = new Array();
  23995. // Skeletons
  23996. this._skeletonsEnabled = true;
  23997. /**
  23998. * The list of skeletons added to the scene
  23999. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24000. */
  24001. this.skeletons = new Array();
  24002. // Morph targets
  24003. /**
  24004. * The list of morph target managers added to the scene
  24005. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24006. */
  24007. this.morphTargetManagers = new Array();
  24008. // Lens flares
  24009. /**
  24010. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24011. */
  24012. this.lensFlaresEnabled = true;
  24013. /**
  24014. * The list of lens flare system added to the scene
  24015. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24016. */
  24017. this.lensFlareSystems = new Array();
  24018. // Collisions
  24019. /**
  24020. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24021. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24022. */
  24023. this.collisionsEnabled = true;
  24024. /**
  24025. * Defines the gravity applied to this scene (used only for collisions)
  24026. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24027. */
  24028. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24029. // Postprocesses
  24030. /**
  24031. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24032. */
  24033. this.postProcessesEnabled = true;
  24034. /**
  24035. * The list of postprocesses added to the scene
  24036. */
  24037. this.postProcesses = new Array();
  24038. // Customs render targets
  24039. /**
  24040. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24041. */
  24042. this.renderTargetsEnabled = true;
  24043. /**
  24044. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24045. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24046. */
  24047. this.dumpNextRenderTargets = false;
  24048. /**
  24049. * The list of user defined render targets added to the scene
  24050. */
  24051. this.customRenderTargets = new Array();
  24052. /**
  24053. * Gets the list of meshes imported to the scene through SceneLoader
  24054. */
  24055. this.importedMeshesFiles = new Array();
  24056. // Probes
  24057. /**
  24058. * Gets or sets a boolean indicating if probes are enabled on this scene
  24059. */
  24060. this.probesEnabled = true;
  24061. /**
  24062. * The list of reflection probes added to the scene
  24063. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24064. */
  24065. this.reflectionProbes = new Array();
  24066. /** @hidden */
  24067. this._actionManagers = new Array();
  24068. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24069. // Procedural textures
  24070. /**
  24071. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24072. */
  24073. this.proceduralTexturesEnabled = true;
  24074. /**
  24075. * The list of procedural textures added to the scene
  24076. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24077. */
  24078. this.proceduralTextures = new Array();
  24079. /**
  24080. * The list of sound tracks added to the scene
  24081. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24082. */
  24083. this.soundTracks = new Array();
  24084. this._audioEnabled = true;
  24085. this._headphone = false;
  24086. // Performance counters
  24087. this._totalVertices = new BABYLON.PerfCounter();
  24088. /** @hidden */
  24089. this._activeIndices = new BABYLON.PerfCounter();
  24090. /** @hidden */
  24091. this._activeParticles = new BABYLON.PerfCounter();
  24092. /** @hidden */
  24093. this._activeBones = new BABYLON.PerfCounter();
  24094. this._animationTime = 0;
  24095. /**
  24096. * Gets or sets a general scale for animation speed
  24097. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24098. */
  24099. this.animationTimeScale = 1;
  24100. this._renderId = 0;
  24101. this._executeWhenReadyTimeoutId = -1;
  24102. this._intermediateRendering = false;
  24103. this._viewUpdateFlag = -1;
  24104. this._projectionUpdateFlag = -1;
  24105. this._alternateViewUpdateFlag = -1;
  24106. this._alternateProjectionUpdateFlag = -1;
  24107. /** @hidden */
  24108. this._toBeDisposed = new BABYLON.SmartArray(256);
  24109. this._activeRequests = new Array();
  24110. this._pendingData = new Array();
  24111. this._isDisposed = false;
  24112. /**
  24113. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24114. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24115. */
  24116. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24117. this._activeMeshes = new BABYLON.SmartArray(256);
  24118. this._processedMaterials = new BABYLON.SmartArray(256);
  24119. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24120. /** @hidden */
  24121. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24122. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24123. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24124. /** @hidden */
  24125. this._activeAnimatables = new Array();
  24126. this._transformMatrix = BABYLON.Matrix.Zero();
  24127. this._useAlternateCameraConfiguration = false;
  24128. this._alternateRendering = false;
  24129. /**
  24130. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24131. * This is useful if there are more lights that the maximum simulteanous authorized
  24132. */
  24133. this.requireLightSorting = false;
  24134. this._depthRenderer = {};
  24135. this._activeMeshesFrozen = false;
  24136. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24137. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24138. this._engine.scenes.push(this);
  24139. this._uid = null;
  24140. this._renderingManager = new BABYLON.RenderingManager(this);
  24141. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24142. if (BABYLON.OutlineRenderer) {
  24143. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24144. }
  24145. if (BABYLON.Tools.IsWindowObjectExist()) {
  24146. this.attachControl();
  24147. }
  24148. //simplification queue
  24149. if (BABYLON.SimplificationQueue) {
  24150. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24151. }
  24152. //collision coordinator initialization. For now legacy per default.
  24153. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24154. // Uniform Buffer
  24155. this._createUbo();
  24156. // Default Image processing definition.
  24157. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24158. }
  24159. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24160. /** The fog is deactivated */
  24161. get: function () {
  24162. return Scene._FOGMODE_NONE;
  24163. },
  24164. enumerable: true,
  24165. configurable: true
  24166. });
  24167. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24168. /** The fog density is following an exponential function */
  24169. get: function () {
  24170. return Scene._FOGMODE_EXP;
  24171. },
  24172. enumerable: true,
  24173. configurable: true
  24174. });
  24175. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24176. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24177. get: function () {
  24178. return Scene._FOGMODE_EXP2;
  24179. },
  24180. enumerable: true,
  24181. configurable: true
  24182. });
  24183. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24184. /** The fog density is following a linear function. */
  24185. get: function () {
  24186. return Scene._FOGMODE_LINEAR;
  24187. },
  24188. enumerable: true,
  24189. configurable: true
  24190. });
  24191. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24192. /**
  24193. * Texture used in all pbr material as the reflection texture.
  24194. * As in the majority of the scene they are the same (exception for multi room and so on),
  24195. * this is easier to reference from here than from all the materials.
  24196. */
  24197. get: function () {
  24198. return this._environmentTexture;
  24199. },
  24200. /**
  24201. * Texture used in all pbr material as the reflection texture.
  24202. * As in the majority of the scene they are the same (exception for multi room and so on),
  24203. * this is easier to set here than in all the materials.
  24204. */
  24205. set: function (value) {
  24206. if (this._environmentTexture === value) {
  24207. return;
  24208. }
  24209. this._environmentTexture = value;
  24210. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24211. },
  24212. enumerable: true,
  24213. configurable: true
  24214. });
  24215. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24216. /**
  24217. * Default image processing configuration used either in the rendering
  24218. * Forward main pass or through the imageProcessingPostProcess if present.
  24219. * As in the majority of the scene they are the same (exception for multi camera),
  24220. * this is easier to reference from here than from all the materials and post process.
  24221. *
  24222. * No setter as we it is a shared configuration, you can set the values instead.
  24223. */
  24224. get: function () {
  24225. return this._imageProcessingConfiguration;
  24226. },
  24227. enumerable: true,
  24228. configurable: true
  24229. });
  24230. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24231. get: function () {
  24232. return this._forceWireframe;
  24233. },
  24234. /**
  24235. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24236. */
  24237. set: function (value) {
  24238. if (this._forceWireframe === value) {
  24239. return;
  24240. }
  24241. this._forceWireframe = value;
  24242. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24248. get: function () {
  24249. return this._forcePointsCloud;
  24250. },
  24251. /**
  24252. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24253. */
  24254. set: function (value) {
  24255. if (this._forcePointsCloud === value) {
  24256. return;
  24257. }
  24258. this._forcePointsCloud = value;
  24259. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24260. },
  24261. enumerable: true,
  24262. configurable: true
  24263. });
  24264. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24265. /**
  24266. * Gets or sets the animation properties override
  24267. */
  24268. get: function () {
  24269. return this._animationPropertiesOverride;
  24270. },
  24271. set: function (value) {
  24272. this._animationPropertiesOverride = value;
  24273. },
  24274. enumerable: true,
  24275. configurable: true
  24276. });
  24277. Object.defineProperty(Scene.prototype, "onDispose", {
  24278. /** Sets a function to be executed when this scene is disposed. */
  24279. set: function (callback) {
  24280. if (this._onDisposeObserver) {
  24281. this.onDisposeObservable.remove(this._onDisposeObserver);
  24282. }
  24283. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24284. },
  24285. enumerable: true,
  24286. configurable: true
  24287. });
  24288. Object.defineProperty(Scene.prototype, "beforeRender", {
  24289. /** Sets a function to be executed before rendering this scene */
  24290. set: function (callback) {
  24291. if (this._onBeforeRenderObserver) {
  24292. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24293. }
  24294. if (callback) {
  24295. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24296. }
  24297. },
  24298. enumerable: true,
  24299. configurable: true
  24300. });
  24301. Object.defineProperty(Scene.prototype, "afterRender", {
  24302. /** Sets a function to be executed after rendering this scene */
  24303. set: function (callback) {
  24304. if (this._onAfterRenderObserver) {
  24305. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24306. }
  24307. if (callback) {
  24308. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24309. }
  24310. },
  24311. enumerable: true,
  24312. configurable: true
  24313. });
  24314. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24315. /** Sets a function to be executed before rendering a camera*/
  24316. set: function (callback) {
  24317. if (this._onBeforeCameraRenderObserver) {
  24318. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24319. }
  24320. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24321. },
  24322. enumerable: true,
  24323. configurable: true
  24324. });
  24325. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24326. /** Sets a function to be executed after rendering a camera*/
  24327. set: function (callback) {
  24328. if (this._onAfterCameraRenderObserver) {
  24329. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24330. }
  24331. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24332. },
  24333. enumerable: true,
  24334. configurable: true
  24335. });
  24336. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24337. /**
  24338. * Gets the gamepad manager associated with the scene
  24339. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24340. */
  24341. get: function () {
  24342. if (!this._gamepadManager) {
  24343. this._gamepadManager = new BABYLON.GamepadManager(this);
  24344. }
  24345. return this._gamepadManager;
  24346. },
  24347. enumerable: true,
  24348. configurable: true
  24349. });
  24350. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24351. /**
  24352. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24353. */
  24354. get: function () {
  24355. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24356. },
  24357. enumerable: true,
  24358. configurable: true
  24359. });
  24360. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24361. get: function () {
  24362. return this._useRightHandedSystem;
  24363. },
  24364. /**
  24365. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24366. */
  24367. set: function (value) {
  24368. if (this._useRightHandedSystem === value) {
  24369. return;
  24370. }
  24371. this._useRightHandedSystem = value;
  24372. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24373. },
  24374. enumerable: true,
  24375. configurable: true
  24376. });
  24377. /**
  24378. * Sets the step Id used by deterministic lock step
  24379. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24380. * @param newStepId defines the step Id
  24381. */
  24382. Scene.prototype.setStepId = function (newStepId) {
  24383. this._currentStepId = newStepId;
  24384. };
  24385. ;
  24386. /**
  24387. * Gets the step Id used by deterministic lock step
  24388. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24389. * @returns the step Id
  24390. */
  24391. Scene.prototype.getStepId = function () {
  24392. return this._currentStepId;
  24393. };
  24394. ;
  24395. /**
  24396. * Gets the internal step used by deterministic lock step
  24397. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24398. * @returns the internal step
  24399. */
  24400. Scene.prototype.getInternalStep = function () {
  24401. return this._currentInternalStep;
  24402. };
  24403. ;
  24404. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24405. get: function () {
  24406. return this._fogEnabled;
  24407. },
  24408. /**
  24409. * Gets or sets a boolean indicating if fog is enabled on this scene
  24410. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24411. */
  24412. set: function (value) {
  24413. if (this._fogEnabled === value) {
  24414. return;
  24415. }
  24416. this._fogEnabled = value;
  24417. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24418. },
  24419. enumerable: true,
  24420. configurable: true
  24421. });
  24422. Object.defineProperty(Scene.prototype, "fogMode", {
  24423. get: function () {
  24424. return this._fogMode;
  24425. },
  24426. /**
  24427. * Gets or sets the fog mode to use
  24428. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24429. */
  24430. set: function (value) {
  24431. if (this._fogMode === value) {
  24432. return;
  24433. }
  24434. this._fogMode = value;
  24435. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24436. },
  24437. enumerable: true,
  24438. configurable: true
  24439. });
  24440. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24441. get: function () {
  24442. return this._shadowsEnabled;
  24443. },
  24444. /**
  24445. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24446. */
  24447. set: function (value) {
  24448. if (this._shadowsEnabled === value) {
  24449. return;
  24450. }
  24451. this._shadowsEnabled = value;
  24452. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24453. },
  24454. enumerable: true,
  24455. configurable: true
  24456. });
  24457. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24458. get: function () {
  24459. return this._lightsEnabled;
  24460. },
  24461. /**
  24462. * Gets or sets a boolean indicating if lights are enabled on this scene
  24463. */
  24464. set: function (value) {
  24465. if (this._lightsEnabled === value) {
  24466. return;
  24467. }
  24468. this._lightsEnabled = value;
  24469. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24470. },
  24471. enumerable: true,
  24472. configurable: true
  24473. });
  24474. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24475. /** The default material used on meshes when no material is affected */
  24476. get: function () {
  24477. if (!this._defaultMaterial) {
  24478. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24479. }
  24480. return this._defaultMaterial;
  24481. },
  24482. /** The default material used on meshes when no material is affected */
  24483. set: function (value) {
  24484. this._defaultMaterial = value;
  24485. },
  24486. enumerable: true,
  24487. configurable: true
  24488. });
  24489. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24490. get: function () {
  24491. return this._texturesEnabled;
  24492. },
  24493. /**
  24494. * Gets or sets a boolean indicating if textures are enabled on this scene
  24495. */
  24496. set: function (value) {
  24497. if (this._texturesEnabled === value) {
  24498. return;
  24499. }
  24500. this._texturesEnabled = value;
  24501. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24502. },
  24503. enumerable: true,
  24504. configurable: true
  24505. });
  24506. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24507. get: function () {
  24508. return this._skeletonsEnabled;
  24509. },
  24510. /**
  24511. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24512. */
  24513. set: function (value) {
  24514. if (this._skeletonsEnabled === value) {
  24515. return;
  24516. }
  24517. this._skeletonsEnabled = value;
  24518. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24524. /**
  24525. * Gets the postprocess render pipeline manager
  24526. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24527. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24528. */
  24529. get: function () {
  24530. if (!this._postProcessRenderPipelineManager) {
  24531. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24532. }
  24533. return this._postProcessRenderPipelineManager;
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24539. /**
  24540. * Gets the main soundtrack associated with the scene
  24541. */
  24542. get: function () {
  24543. if (!this._mainSoundTrack) {
  24544. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24545. }
  24546. return this._mainSoundTrack;
  24547. },
  24548. enumerable: true,
  24549. configurable: true
  24550. });
  24551. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24552. /** @hidden */
  24553. get: function () {
  24554. return this._alternateRendering;
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24560. /**
  24561. * Gets the list of frustum planes (built from the active camera)
  24562. */
  24563. get: function () {
  24564. return this._frustumPlanes;
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24570. /**
  24571. * Gets the current geometry buffer associated to the scene.
  24572. */
  24573. get: function () {
  24574. return this._geometryBufferRenderer;
  24575. },
  24576. /**
  24577. * Sets the current geometry buffer for the scene.
  24578. */
  24579. set: function (geometryBufferRenderer) {
  24580. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24581. this._geometryBufferRenderer = geometryBufferRenderer;
  24582. }
  24583. },
  24584. enumerable: true,
  24585. configurable: true
  24586. });
  24587. Object.defineProperty(Scene.prototype, "debugLayer", {
  24588. /**
  24589. * Gets the debug layer associated with the scene
  24590. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24591. */
  24592. get: function () {
  24593. if (!this._debugLayer) {
  24594. this._debugLayer = new BABYLON.DebugLayer(this);
  24595. }
  24596. return this._debugLayer;
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24602. /**
  24603. * Gets a boolean indicating if collisions are processed on a web worker
  24604. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24605. */
  24606. get: function () {
  24607. return this._workerCollisions;
  24608. },
  24609. set: function (enabled) {
  24610. if (!BABYLON.CollisionCoordinatorLegacy) {
  24611. return;
  24612. }
  24613. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24614. this._workerCollisions = enabled;
  24615. if (this.collisionCoordinator) {
  24616. this.collisionCoordinator.destroy();
  24617. }
  24618. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24619. this.collisionCoordinator.init(this);
  24620. },
  24621. enumerable: true,
  24622. configurable: true
  24623. });
  24624. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24625. /**
  24626. * Gets the octree used to boost mesh selection (picking)
  24627. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24628. */
  24629. get: function () {
  24630. return this._selectionOctree;
  24631. },
  24632. enumerable: true,
  24633. configurable: true
  24634. });
  24635. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24636. /**
  24637. * Gets the mesh that is currently under the pointer
  24638. */
  24639. get: function () {
  24640. return this._pointerOverMesh;
  24641. },
  24642. enumerable: true,
  24643. configurable: true
  24644. });
  24645. Object.defineProperty(Scene.prototype, "pointerX", {
  24646. /**
  24647. * Gets the current on-screen X position of the pointer
  24648. */
  24649. get: function () {
  24650. return this._pointerX;
  24651. },
  24652. enumerable: true,
  24653. configurable: true
  24654. });
  24655. Object.defineProperty(Scene.prototype, "pointerY", {
  24656. /**
  24657. * Gets the current on-screen Y position of the pointer
  24658. */
  24659. get: function () {
  24660. return this._pointerY;
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. /**
  24666. * Gets the cached material (ie. the latest rendered one)
  24667. * @returns the cached material
  24668. */
  24669. Scene.prototype.getCachedMaterial = function () {
  24670. return this._cachedMaterial;
  24671. };
  24672. /**
  24673. * Gets the cached effect (ie. the latest rendered one)
  24674. * @returns the cached effect
  24675. */
  24676. Scene.prototype.getCachedEffect = function () {
  24677. return this._cachedEffect;
  24678. };
  24679. /**
  24680. * Gets the cached visibility state (ie. the latest rendered one)
  24681. * @returns the cached visibility state
  24682. */
  24683. Scene.prototype.getCachedVisibility = function () {
  24684. return this._cachedVisibility;
  24685. };
  24686. /**
  24687. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24688. * @param material defines the current material
  24689. * @param effect defines the current effect
  24690. * @param visibility defines the current visibility state
  24691. * @returns true if one parameter is not cached
  24692. */
  24693. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24694. if (visibility === void 0) { visibility = 1; }
  24695. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24696. };
  24697. /**
  24698. * Gets the bounding box renderer associated with the scene
  24699. * @returns a BoundingBoxRenderer
  24700. */
  24701. Scene.prototype.getBoundingBoxRenderer = function () {
  24702. if (!this._boundingBoxRenderer) {
  24703. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24704. }
  24705. return this._boundingBoxRenderer;
  24706. };
  24707. /**
  24708. * Gets the outline renderer associated with the scene
  24709. * @returns a OutlineRenderer
  24710. */
  24711. Scene.prototype.getOutlineRenderer = function () {
  24712. return this._outlineRenderer;
  24713. };
  24714. /**
  24715. * Gets the engine associated with the scene
  24716. * @returns an Engine
  24717. */
  24718. Scene.prototype.getEngine = function () {
  24719. return this._engine;
  24720. };
  24721. /**
  24722. * Gets the total number of vertices rendered per frame
  24723. * @returns the total number of vertices rendered per frame
  24724. */
  24725. Scene.prototype.getTotalVertices = function () {
  24726. return this._totalVertices.current;
  24727. };
  24728. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24729. /**
  24730. * Gets the performance counter for total vertices
  24731. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24732. */
  24733. get: function () {
  24734. return this._totalVertices;
  24735. },
  24736. enumerable: true,
  24737. configurable: true
  24738. });
  24739. /**
  24740. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24741. * @returns the total number of active indices rendered per frame
  24742. */
  24743. Scene.prototype.getActiveIndices = function () {
  24744. return this._activeIndices.current;
  24745. };
  24746. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24747. /**
  24748. * Gets the performance counter for active indices
  24749. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24750. */
  24751. get: function () {
  24752. return this._activeIndices;
  24753. },
  24754. enumerable: true,
  24755. configurable: true
  24756. });
  24757. /**
  24758. * Gets the total number of active particles rendered per frame
  24759. * @returns the total number of active particles rendered per frame
  24760. */
  24761. Scene.prototype.getActiveParticles = function () {
  24762. return this._activeParticles.current;
  24763. };
  24764. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24765. /**
  24766. * Gets the performance counter for active particles
  24767. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24768. */
  24769. get: function () {
  24770. return this._activeParticles;
  24771. },
  24772. enumerable: true,
  24773. configurable: true
  24774. });
  24775. /**
  24776. * Gets the total number of active bones rendered per frame
  24777. * @returns the total number of active bones rendered per frame
  24778. */
  24779. Scene.prototype.getActiveBones = function () {
  24780. return this._activeBones.current;
  24781. };
  24782. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24783. /**
  24784. * Gets the performance counter for active bones
  24785. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24786. */
  24787. get: function () {
  24788. return this._activeBones;
  24789. },
  24790. enumerable: true,
  24791. configurable: true
  24792. });
  24793. /** @hidden */
  24794. Scene.prototype.getInterFramePerfCounter = function () {
  24795. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24796. return 0;
  24797. };
  24798. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24799. /** @hidden */
  24800. get: function () {
  24801. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24802. return null;
  24803. },
  24804. enumerable: true,
  24805. configurable: true
  24806. });
  24807. /** @hidden */
  24808. Scene.prototype.getLastFrameDuration = function () {
  24809. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24810. return 0;
  24811. };
  24812. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24813. /** @hidden */
  24814. get: function () {
  24815. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24816. return null;
  24817. },
  24818. enumerable: true,
  24819. configurable: true
  24820. });
  24821. /** @hidden */
  24822. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24823. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24824. return 0;
  24825. };
  24826. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24827. /** @hidden */
  24828. get: function () {
  24829. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24830. return null;
  24831. },
  24832. enumerable: true,
  24833. configurable: true
  24834. });
  24835. /**
  24836. * Gets the array of active meshes
  24837. * @returns an array of AbstractMesh
  24838. */
  24839. Scene.prototype.getActiveMeshes = function () {
  24840. return this._activeMeshes;
  24841. };
  24842. /** @hidden */
  24843. Scene.prototype.getRenderTargetsDuration = function () {
  24844. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24845. return 0;
  24846. };
  24847. /** @hidden */
  24848. Scene.prototype.getRenderDuration = function () {
  24849. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24850. return 0;
  24851. };
  24852. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24853. /** @hidden */
  24854. get: function () {
  24855. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24856. return null;
  24857. },
  24858. enumerable: true,
  24859. configurable: true
  24860. });
  24861. /** @hidden */
  24862. Scene.prototype.getParticlesDuration = function () {
  24863. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24864. return 0;
  24865. };
  24866. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24867. /** @hidden */
  24868. get: function () {
  24869. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24870. return null;
  24871. },
  24872. enumerable: true,
  24873. configurable: true
  24874. });
  24875. /** @hidden */
  24876. Scene.prototype.getSpritesDuration = function () {
  24877. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24878. return 0;
  24879. };
  24880. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24881. /** @hidden */
  24882. get: function () {
  24883. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24884. return null;
  24885. },
  24886. enumerable: true,
  24887. configurable: true
  24888. });
  24889. /**
  24890. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24891. * @returns a number
  24892. */
  24893. Scene.prototype.getAnimationRatio = function () {
  24894. return this._animationRatio;
  24895. };
  24896. /**
  24897. * Gets an unique Id for the current frame
  24898. * @returns a number
  24899. */
  24900. Scene.prototype.getRenderId = function () {
  24901. return this._renderId;
  24902. };
  24903. /** Call this function if you want to manually increment the render Id*/
  24904. Scene.prototype.incrementRenderId = function () {
  24905. this._renderId++;
  24906. };
  24907. Scene.prototype._updatePointerPosition = function (evt) {
  24908. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24909. if (!canvasRect) {
  24910. return;
  24911. }
  24912. this._pointerX = evt.clientX - canvasRect.left;
  24913. this._pointerY = evt.clientY - canvasRect.top;
  24914. this._unTranslatedPointerX = this._pointerX;
  24915. this._unTranslatedPointerY = this._pointerY;
  24916. };
  24917. Scene.prototype._createUbo = function () {
  24918. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24919. this._sceneUbo.addUniform("viewProjection", 16);
  24920. this._sceneUbo.addUniform("view", 16);
  24921. };
  24922. Scene.prototype._createAlternateUbo = function () {
  24923. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24924. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24925. this._alternateSceneUbo.addUniform("view", 16);
  24926. };
  24927. // Pointers handling
  24928. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24929. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24930. if (result) {
  24931. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24932. }
  24933. return result;
  24934. };
  24935. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24936. if (pointerInfo.pickInfo) {
  24937. if (!pointerInfo.pickInfo.ray) {
  24938. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24939. }
  24940. }
  24941. };
  24942. /**
  24943. * Use this method to simulate a pointer move on a mesh
  24944. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24945. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24946. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24947. * @returns the current scene
  24948. */
  24949. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24950. var evt = new PointerEvent("pointermove", pointerEventInit);
  24951. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24952. return this;
  24953. }
  24954. return this._processPointerMove(pickResult, evt);
  24955. };
  24956. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24957. var canvas = this._engine.getRenderingCanvas();
  24958. if (!canvas) {
  24959. return this;
  24960. }
  24961. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24962. this.setPointerOverSprite(null);
  24963. this.setPointerOverMesh(pickResult.pickedMesh);
  24964. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24965. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24966. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24967. }
  24968. else {
  24969. canvas.style.cursor = this.hoverCursor;
  24970. }
  24971. }
  24972. else {
  24973. canvas.style.cursor = this.defaultCursor;
  24974. }
  24975. }
  24976. else {
  24977. this.setPointerOverMesh(null);
  24978. // Sprites
  24979. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24980. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24981. this.setPointerOverSprite(pickResult.pickedSprite);
  24982. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24983. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24984. }
  24985. else {
  24986. canvas.style.cursor = this.hoverCursor;
  24987. }
  24988. }
  24989. else {
  24990. this.setPointerOverSprite(null);
  24991. // Restore pointer
  24992. canvas.style.cursor = this.defaultCursor;
  24993. }
  24994. }
  24995. if (pickResult) {
  24996. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24997. if (this.onPointerMove) {
  24998. this.onPointerMove(evt, pickResult, type);
  24999. }
  25000. if (this.onPointerObservable.hasObservers()) {
  25001. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25002. this._setRayOnPointerInfo(pi);
  25003. this.onPointerObservable.notifyObservers(pi, type);
  25004. }
  25005. }
  25006. return this;
  25007. };
  25008. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25009. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25010. if (pickResult) {
  25011. pi.ray = pickResult.ray;
  25012. }
  25013. this.onPrePointerObservable.notifyObservers(pi, type);
  25014. if (pi.skipOnPointerObservable) {
  25015. return true;
  25016. }
  25017. else {
  25018. return false;
  25019. }
  25020. };
  25021. /**
  25022. * Use this method to simulate a pointer down on a mesh
  25023. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25024. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25025. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25026. * @returns the current scene
  25027. */
  25028. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25029. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25030. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25031. return this;
  25032. }
  25033. return this._processPointerDown(pickResult, evt);
  25034. };
  25035. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25036. var _this = this;
  25037. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25038. this._pickedDownMesh = pickResult.pickedMesh;
  25039. var actionManager = pickResult.pickedMesh.actionManager;
  25040. if (actionManager) {
  25041. if (actionManager.hasPickTriggers) {
  25042. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25043. switch (evt.button) {
  25044. case 0:
  25045. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25046. break;
  25047. case 1:
  25048. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25049. break;
  25050. case 2:
  25051. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25052. break;
  25053. }
  25054. }
  25055. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25056. window.setTimeout(function () {
  25057. 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);
  25058. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25059. if (_this._totalPointersPressed !== 0 &&
  25060. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25061. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25062. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25063. _this._startingPointerTime = 0;
  25064. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25065. }
  25066. }
  25067. }, Scene.LongPressDelay);
  25068. }
  25069. }
  25070. }
  25071. if (pickResult) {
  25072. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25073. if (this.onPointerDown) {
  25074. this.onPointerDown(evt, pickResult, type);
  25075. }
  25076. if (this.onPointerObservable.hasObservers()) {
  25077. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25078. this._setRayOnPointerInfo(pi);
  25079. this.onPointerObservable.notifyObservers(pi, type);
  25080. }
  25081. }
  25082. return this;
  25083. };
  25084. /**
  25085. * Use this method to simulate a pointer up on a mesh
  25086. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25087. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25088. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25089. * @returns the current scene
  25090. */
  25091. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25092. var evt = new PointerEvent("pointerup", pointerEventInit);
  25093. var clickInfo = new ClickInfo();
  25094. clickInfo.singleClick = true;
  25095. clickInfo.ignore = true;
  25096. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25097. return this;
  25098. }
  25099. return this._processPointerUp(pickResult, evt, clickInfo);
  25100. };
  25101. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25102. if (pickResult && pickResult && pickResult.pickedMesh) {
  25103. this._pickedUpMesh = pickResult.pickedMesh;
  25104. if (this._pickedDownMesh === this._pickedUpMesh) {
  25105. if (this.onPointerPick) {
  25106. this.onPointerPick(evt, pickResult);
  25107. }
  25108. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25109. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25110. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25111. this._setRayOnPointerInfo(pi);
  25112. this.onPointerObservable.notifyObservers(pi, type_1);
  25113. }
  25114. }
  25115. if (pickResult.pickedMesh.actionManager) {
  25116. if (clickInfo.ignore) {
  25117. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25118. }
  25119. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25120. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25121. }
  25122. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25123. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25124. }
  25125. }
  25126. }
  25127. if (this._pickedDownMesh &&
  25128. this._pickedDownMesh.actionManager &&
  25129. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25130. this._pickedDownMesh !== this._pickedUpMesh) {
  25131. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25132. }
  25133. var type = BABYLON.PointerEventTypes.POINTERUP;
  25134. if (this.onPointerObservable.hasObservers()) {
  25135. if (!clickInfo.ignore) {
  25136. if (!clickInfo.hasSwiped) {
  25137. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25138. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25139. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25140. this._setRayOnPointerInfo(pi);
  25141. this.onPointerObservable.notifyObservers(pi, type_2);
  25142. }
  25143. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25144. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25145. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25146. this._setRayOnPointerInfo(pi);
  25147. this.onPointerObservable.notifyObservers(pi, type_3);
  25148. }
  25149. }
  25150. }
  25151. else {
  25152. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25153. this._setRayOnPointerInfo(pi);
  25154. this.onPointerObservable.notifyObservers(pi, type);
  25155. }
  25156. }
  25157. if (this.onPointerUp) {
  25158. this.onPointerUp(evt, pickResult, type);
  25159. }
  25160. return this;
  25161. };
  25162. /**
  25163. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25164. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25165. * @returns true if the pointer was captured
  25166. */
  25167. Scene.prototype.isPointerCaptured = function (pointerId) {
  25168. if (pointerId === void 0) { pointerId = 0; }
  25169. return this._pointerCaptures[pointerId];
  25170. };
  25171. /**
  25172. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25173. * @param attachUp defines if you want to attach events to pointerup
  25174. * @param attachDown defines if you want to attach events to pointerdown
  25175. * @param attachMove defines if you want to attach events to pointermove
  25176. */
  25177. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25178. var _this = this;
  25179. if (attachUp === void 0) { attachUp = true; }
  25180. if (attachDown === void 0) { attachDown = true; }
  25181. if (attachMove === void 0) { attachMove = true; }
  25182. this._initActionManager = function (act, clickInfo) {
  25183. if (!_this._meshPickProceed) {
  25184. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25185. _this._currentPickResult = pickResult;
  25186. if (pickResult) {
  25187. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25188. }
  25189. _this._meshPickProceed = true;
  25190. }
  25191. return act;
  25192. };
  25193. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25194. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25195. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25196. btn !== _this._previousButtonPressed) {
  25197. _this._doubleClickOccured = false;
  25198. clickInfo.singleClick = true;
  25199. clickInfo.ignore = false;
  25200. cb(clickInfo, _this._currentPickResult);
  25201. }
  25202. };
  25203. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25204. var clickInfo = new ClickInfo();
  25205. _this._currentPickResult = null;
  25206. var act = null;
  25207. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25208. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25209. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25210. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25211. act = _this._initActionManager(act, clickInfo);
  25212. if (act)
  25213. checkPicking = act.hasPickTriggers;
  25214. }
  25215. if (checkPicking) {
  25216. var btn = evt.button;
  25217. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25218. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25219. if (!clickInfo.hasSwiped) {
  25220. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25221. if (!checkSingleClickImmediately) {
  25222. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25223. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25224. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25225. act = _this._initActionManager(act, clickInfo);
  25226. if (act)
  25227. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25228. }
  25229. }
  25230. if (checkSingleClickImmediately) {
  25231. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25232. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25233. btn !== _this._previousButtonPressed) {
  25234. clickInfo.singleClick = true;
  25235. cb(clickInfo, _this._currentPickResult);
  25236. }
  25237. }
  25238. // at least one double click is required to be check and exclusive double click is enabled
  25239. else {
  25240. // wait that no double click has been raised during the double click delay
  25241. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25242. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25243. }
  25244. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25245. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25246. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25247. act = _this._initActionManager(act, clickInfo);
  25248. if (act)
  25249. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25250. }
  25251. if (checkDoubleClick) {
  25252. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25253. if (btn === _this._previousButtonPressed &&
  25254. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25255. !_this._doubleClickOccured) {
  25256. // pointer has not moved for 2 clicks, it's a double click
  25257. if (!clickInfo.hasSwiped &&
  25258. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25259. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25260. _this._previousStartingPointerTime = 0;
  25261. _this._doubleClickOccured = true;
  25262. clickInfo.doubleClick = true;
  25263. clickInfo.ignore = false;
  25264. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25265. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25266. }
  25267. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25268. cb(clickInfo, _this._currentPickResult);
  25269. }
  25270. // if the two successive clicks are too far, it's just two simple clicks
  25271. else {
  25272. _this._doubleClickOccured = false;
  25273. _this._previousStartingPointerTime = _this._startingPointerTime;
  25274. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25275. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25276. _this._previousButtonPressed = btn;
  25277. if (Scene.ExclusiveDoubleClickMode) {
  25278. if (_this._previousDelayedSimpleClickTimeout) {
  25279. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25280. }
  25281. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25282. cb(clickInfo, _this._previousPickResult);
  25283. }
  25284. else {
  25285. cb(clickInfo, _this._currentPickResult);
  25286. }
  25287. }
  25288. }
  25289. // just the first click of the double has been raised
  25290. else {
  25291. _this._doubleClickOccured = false;
  25292. _this._previousStartingPointerTime = _this._startingPointerTime;
  25293. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25294. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25295. _this._previousButtonPressed = btn;
  25296. }
  25297. }
  25298. }
  25299. }
  25300. clickInfo.ignore = true;
  25301. cb(clickInfo, _this._currentPickResult);
  25302. };
  25303. this._spritePredicate = function (sprite) {
  25304. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25305. };
  25306. this._onPointerMove = function (evt) {
  25307. _this._updatePointerPosition(evt);
  25308. // PreObservable support
  25309. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25310. return;
  25311. }
  25312. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25313. return;
  25314. }
  25315. if (!_this.pointerMovePredicate) {
  25316. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25317. }
  25318. // Meshes
  25319. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25320. _this._processPointerMove(pickResult, evt);
  25321. };
  25322. this._onPointerDown = function (evt) {
  25323. _this._totalPointersPressed++;
  25324. _this._pickedDownMesh = null;
  25325. _this._meshPickProceed = false;
  25326. _this._updatePointerPosition(evt);
  25327. if (_this.preventDefaultOnPointerDown && canvas) {
  25328. evt.preventDefault();
  25329. canvas.focus();
  25330. }
  25331. // PreObservable support
  25332. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25333. return;
  25334. }
  25335. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25336. return;
  25337. }
  25338. _this._pointerCaptures[evt.pointerId] = true;
  25339. _this._startingPointerPosition.x = _this._pointerX;
  25340. _this._startingPointerPosition.y = _this._pointerY;
  25341. _this._startingPointerTime = Date.now();
  25342. if (!_this.pointerDownPredicate) {
  25343. _this.pointerDownPredicate = function (mesh) {
  25344. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25345. };
  25346. }
  25347. // Meshes
  25348. _this._pickedDownMesh = null;
  25349. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25350. _this._processPointerDown(pickResult, evt);
  25351. // Sprites
  25352. _this._pickedDownSprite = null;
  25353. if (_this.spriteManagers.length > 0) {
  25354. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25355. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25356. if (pickResult.pickedSprite.actionManager) {
  25357. _this._pickedDownSprite = pickResult.pickedSprite;
  25358. switch (evt.button) {
  25359. case 0:
  25360. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25361. break;
  25362. case 1:
  25363. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25364. break;
  25365. case 2:
  25366. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25367. break;
  25368. }
  25369. if (pickResult.pickedSprite.actionManager) {
  25370. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25371. }
  25372. }
  25373. }
  25374. }
  25375. };
  25376. this._onPointerUp = function (evt) {
  25377. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25378. return; // So we need to test it the pointer down was pressed before.
  25379. }
  25380. _this._totalPointersPressed--;
  25381. _this._pickedUpMesh = null;
  25382. _this._meshPickProceed = false;
  25383. _this._updatePointerPosition(evt);
  25384. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25385. // PreObservable support
  25386. if (_this.onPrePointerObservable.hasObservers()) {
  25387. if (!clickInfo.ignore) {
  25388. if (!clickInfo.hasSwiped) {
  25389. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25390. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25391. return;
  25392. }
  25393. }
  25394. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25395. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25396. return;
  25397. }
  25398. }
  25399. }
  25400. }
  25401. else {
  25402. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25403. return;
  25404. }
  25405. }
  25406. }
  25407. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25408. return;
  25409. }
  25410. _this._pointerCaptures[evt.pointerId] = false;
  25411. if (!_this.pointerUpPredicate) {
  25412. _this.pointerUpPredicate = function (mesh) {
  25413. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25414. };
  25415. }
  25416. // Meshes
  25417. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25418. _this._initActionManager(null, clickInfo);
  25419. }
  25420. if (!pickResult) {
  25421. pickResult = _this._currentPickResult;
  25422. }
  25423. _this._processPointerUp(pickResult, evt, clickInfo);
  25424. // Sprites
  25425. if (!clickInfo.ignore) {
  25426. if (_this.spriteManagers.length > 0) {
  25427. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25428. if (spritePickResult) {
  25429. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25430. if (spritePickResult.pickedSprite.actionManager) {
  25431. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25432. if (spritePickResult.pickedSprite.actionManager) {
  25433. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25434. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25435. }
  25436. }
  25437. }
  25438. }
  25439. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25440. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25441. }
  25442. }
  25443. }
  25444. }
  25445. _this._previousPickResult = _this._currentPickResult;
  25446. });
  25447. };
  25448. this._onKeyDown = function (evt) {
  25449. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25450. if (_this.onPreKeyboardObservable.hasObservers()) {
  25451. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25452. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25453. if (pi.skipOnPointerObservable) {
  25454. return;
  25455. }
  25456. }
  25457. if (_this.onKeyboardObservable.hasObservers()) {
  25458. var pi = new BABYLON.KeyboardInfo(type, evt);
  25459. _this.onKeyboardObservable.notifyObservers(pi, type);
  25460. }
  25461. if (_this.actionManager) {
  25462. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25463. }
  25464. };
  25465. this._onKeyUp = function (evt) {
  25466. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25467. if (_this.onPreKeyboardObservable.hasObservers()) {
  25468. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25469. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25470. if (pi.skipOnPointerObservable) {
  25471. return;
  25472. }
  25473. }
  25474. if (_this.onKeyboardObservable.hasObservers()) {
  25475. var pi = new BABYLON.KeyboardInfo(type, evt);
  25476. _this.onKeyboardObservable.notifyObservers(pi, type);
  25477. }
  25478. if (_this.actionManager) {
  25479. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25480. }
  25481. };
  25482. var engine = this.getEngine();
  25483. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25484. if (!canvas) {
  25485. return;
  25486. }
  25487. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25488. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25489. });
  25490. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25491. if (!canvas) {
  25492. return;
  25493. }
  25494. canvas.removeEventListener("keydown", _this._onKeyDown);
  25495. canvas.removeEventListener("keyup", _this._onKeyUp);
  25496. });
  25497. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25498. var canvas = this._engine.getRenderingCanvas();
  25499. if (!canvas) {
  25500. return;
  25501. }
  25502. if (attachMove) {
  25503. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25504. // Wheel
  25505. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25506. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25507. }
  25508. if (attachDown) {
  25509. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25510. }
  25511. if (attachUp) {
  25512. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25513. }
  25514. canvas.tabIndex = 1;
  25515. };
  25516. /** Detaches all event handlers*/
  25517. Scene.prototype.detachControl = function () {
  25518. var engine = this.getEngine();
  25519. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25520. var canvas = engine.getRenderingCanvas();
  25521. if (!canvas) {
  25522. return;
  25523. }
  25524. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25525. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25526. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25527. if (this._onCanvasBlurObserver) {
  25528. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25529. }
  25530. if (this._onCanvasFocusObserver) {
  25531. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25532. }
  25533. // Wheel
  25534. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25535. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25536. // Keyboard
  25537. canvas.removeEventListener("keydown", this._onKeyDown);
  25538. canvas.removeEventListener("keyup", this._onKeyUp);
  25539. // Observables
  25540. this.onKeyboardObservable.clear();
  25541. this.onPreKeyboardObservable.clear();
  25542. this.onPointerObservable.clear();
  25543. this.onPrePointerObservable.clear();
  25544. };
  25545. /**
  25546. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25547. * Delay loaded resources are not taking in account
  25548. * @return true if all required resources are ready
  25549. */
  25550. Scene.prototype.isReady = function () {
  25551. if (this._isDisposed) {
  25552. return false;
  25553. }
  25554. if (this._pendingData.length > 0) {
  25555. return false;
  25556. }
  25557. var index;
  25558. var engine = this.getEngine();
  25559. // Geometries
  25560. for (index = 0; index < this._geometries.length; index++) {
  25561. var geometry = this._geometries[index];
  25562. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25563. return false;
  25564. }
  25565. }
  25566. // Meshes
  25567. for (index = 0; index < this.meshes.length; index++) {
  25568. var mesh = this.meshes[index];
  25569. if (!mesh.isEnabled()) {
  25570. continue;
  25571. }
  25572. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25573. continue;
  25574. }
  25575. if (!mesh.isReady(true)) {
  25576. return false;
  25577. }
  25578. // Effect layers
  25579. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25580. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25581. var layer = _a[_i];
  25582. if (!layer.hasMesh(mesh)) {
  25583. continue;
  25584. }
  25585. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25586. var subMesh = _c[_b];
  25587. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25588. return false;
  25589. }
  25590. }
  25591. }
  25592. }
  25593. // Post-processes
  25594. if (this.activeCameras && this.activeCameras.length > 0) {
  25595. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25596. var camera = _e[_d];
  25597. if (!camera.isReady(true)) {
  25598. return false;
  25599. }
  25600. }
  25601. }
  25602. else if (this.activeCamera) {
  25603. if (!this.activeCamera.isReady(true)) {
  25604. return false;
  25605. }
  25606. }
  25607. // Particles
  25608. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25609. var particleSystem = _g[_f];
  25610. if (!particleSystem.isReady()) {
  25611. return false;
  25612. }
  25613. }
  25614. return true;
  25615. };
  25616. /** Resets all cached information relative to material (including effect and visibility) */
  25617. Scene.prototype.resetCachedMaterial = function () {
  25618. this._cachedMaterial = null;
  25619. this._cachedEffect = null;
  25620. this._cachedVisibility = null;
  25621. };
  25622. /**
  25623. * Registers a function to be called before every frame render
  25624. * @param func defines the function to register
  25625. */
  25626. Scene.prototype.registerBeforeRender = function (func) {
  25627. this.onBeforeRenderObservable.add(func);
  25628. };
  25629. /**
  25630. * Unregisters a function called before every frame render
  25631. * @param func defines the function to unregister
  25632. */
  25633. Scene.prototype.unregisterBeforeRender = function (func) {
  25634. this.onBeforeRenderObservable.removeCallback(func);
  25635. };
  25636. /**
  25637. * Registers a function to be called after every frame render
  25638. * @param func defines the function to register
  25639. */
  25640. Scene.prototype.registerAfterRender = function (func) {
  25641. this.onAfterRenderObservable.add(func);
  25642. };
  25643. /**
  25644. * Unregisters a function called after every frame render
  25645. * @param func defines the function to unregister
  25646. */
  25647. Scene.prototype.unregisterAfterRender = function (func) {
  25648. this.onAfterRenderObservable.removeCallback(func);
  25649. };
  25650. Scene.prototype._executeOnceBeforeRender = function (func) {
  25651. var _this = this;
  25652. var execFunc = function () {
  25653. func();
  25654. setTimeout(function () {
  25655. _this.unregisterBeforeRender(execFunc);
  25656. });
  25657. };
  25658. this.registerBeforeRender(execFunc);
  25659. };
  25660. /**
  25661. * The provided function will run before render once and will be disposed afterwards.
  25662. * A timeout delay can be provided so that the function will be executed in N ms.
  25663. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25664. * @param func The function to be executed.
  25665. * @param timeout optional delay in ms
  25666. */
  25667. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25668. var _this = this;
  25669. if (timeout !== undefined) {
  25670. setTimeout(function () {
  25671. _this._executeOnceBeforeRender(func);
  25672. }, timeout);
  25673. }
  25674. else {
  25675. this._executeOnceBeforeRender(func);
  25676. }
  25677. };
  25678. /** @hidden */
  25679. Scene.prototype._addPendingData = function (data) {
  25680. this._pendingData.push(data);
  25681. };
  25682. /** @hidden */
  25683. Scene.prototype._removePendingData = function (data) {
  25684. var wasLoading = this.isLoading;
  25685. var index = this._pendingData.indexOf(data);
  25686. if (index !== -1) {
  25687. this._pendingData.splice(index, 1);
  25688. }
  25689. if (wasLoading && !this.isLoading) {
  25690. this.onDataLoadedObservable.notifyObservers(this);
  25691. }
  25692. };
  25693. /**
  25694. * Returns the number of items waiting to be loaded
  25695. * @returns the number of items waiting to be loaded
  25696. */
  25697. Scene.prototype.getWaitingItemsCount = function () {
  25698. return this._pendingData.length;
  25699. };
  25700. Object.defineProperty(Scene.prototype, "isLoading", {
  25701. /**
  25702. * Returns a boolean indicating if the scene is still loading data
  25703. */
  25704. get: function () {
  25705. return this._pendingData.length > 0;
  25706. },
  25707. enumerable: true,
  25708. configurable: true
  25709. });
  25710. /**
  25711. * Registers a function to be executed when the scene is ready
  25712. * @param {Function} func - the function to be executed
  25713. */
  25714. Scene.prototype.executeWhenReady = function (func) {
  25715. var _this = this;
  25716. this.onReadyObservable.add(func);
  25717. if (this._executeWhenReadyTimeoutId !== -1) {
  25718. return;
  25719. }
  25720. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25721. _this._checkIsReady();
  25722. }, 150);
  25723. };
  25724. /**
  25725. * Returns a promise that resolves when the scene is ready
  25726. * @returns A promise that resolves when the scene is ready
  25727. */
  25728. Scene.prototype.whenReadyAsync = function () {
  25729. var _this = this;
  25730. return new Promise(function (resolve) {
  25731. _this.executeWhenReady(function () {
  25732. resolve();
  25733. });
  25734. });
  25735. };
  25736. /** @hidden */
  25737. Scene.prototype._checkIsReady = function () {
  25738. var _this = this;
  25739. if (this.isReady()) {
  25740. this.onReadyObservable.notifyObservers(this);
  25741. this.onReadyObservable.clear();
  25742. this._executeWhenReadyTimeoutId = -1;
  25743. return;
  25744. }
  25745. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25746. _this._checkIsReady();
  25747. }, 150);
  25748. };
  25749. // Animations
  25750. /**
  25751. * Will start the animation sequence of a given target
  25752. * @param target defines the target
  25753. * @param from defines from which frame should animation start
  25754. * @param to defines until which frame should animation run.
  25755. * @param weight defines the weight to apply to the animation (1.0 by default)
  25756. * @param loop defines if the animation loops
  25757. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25758. * @param onAnimationEnd defines the function to be executed when the animation ends
  25759. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25760. * @returns the animatable object created for this animation
  25761. */
  25762. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25763. if (weight === void 0) { weight = 1.0; }
  25764. if (speedRatio === void 0) { speedRatio = 1.0; }
  25765. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25766. returnedAnimatable.weight = weight;
  25767. return returnedAnimatable;
  25768. };
  25769. /**
  25770. * Will start the animation sequence of a given target
  25771. * @param target defines the target
  25772. * @param from defines from which frame should animation start
  25773. * @param to defines until which frame should animation run.
  25774. * @param loop defines if the animation loops
  25775. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25776. * @param onAnimationEnd defines the function to be executed when the animation ends
  25777. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25778. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25779. * @returns the animatable object created for this animation
  25780. */
  25781. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25782. if (speedRatio === void 0) { speedRatio = 1.0; }
  25783. if (stopCurrent === void 0) { stopCurrent = true; }
  25784. if (from > to && speedRatio > 0) {
  25785. speedRatio *= -1;
  25786. }
  25787. if (stopCurrent) {
  25788. this.stopAnimation(target);
  25789. }
  25790. if (!animatable) {
  25791. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25792. }
  25793. // Local animations
  25794. if (target.animations) {
  25795. animatable.appendAnimations(target, target.animations);
  25796. }
  25797. // Children animations
  25798. if (target.getAnimatables) {
  25799. var animatables = target.getAnimatables();
  25800. for (var index = 0; index < animatables.length; index++) {
  25801. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25802. }
  25803. }
  25804. animatable.reset();
  25805. return animatable;
  25806. };
  25807. /**
  25808. * Begin a new animation on a given node
  25809. * @param target defines the target where the animation will take place
  25810. * @param animations defines the list of animations to start
  25811. * @param from defines the initial value
  25812. * @param to defines the final value
  25813. * @param loop defines if you want animation to loop (off by default)
  25814. * @param speedRatio defines the speed ratio to apply to all animations
  25815. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25816. * @returns the list of created animatables
  25817. */
  25818. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25819. if (speedRatio === undefined) {
  25820. speedRatio = 1.0;
  25821. }
  25822. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25823. return animatable;
  25824. };
  25825. /**
  25826. * Begin a new animation on a given node and its hierarchy
  25827. * @param target defines the root node where the animation will take place
  25828. * @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.
  25829. * @param animations defines the list of animations to start
  25830. * @param from defines the initial value
  25831. * @param to defines the final value
  25832. * @param loop defines if you want animation to loop (off by default)
  25833. * @param speedRatio defines the speed ratio to apply to all animations
  25834. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25835. * @returns the list of animatables created for all nodes
  25836. */
  25837. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25838. var children = target.getDescendants(directDescendantsOnly);
  25839. var result = [];
  25840. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25841. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25842. var child = children_1[_i];
  25843. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25844. }
  25845. return result;
  25846. };
  25847. /**
  25848. * Gets the animatable associated with a specific target
  25849. * @param target defines the target of the animatable
  25850. * @returns the required animatable if found
  25851. */
  25852. Scene.prototype.getAnimatableByTarget = function (target) {
  25853. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25854. if (this._activeAnimatables[index].target === target) {
  25855. return this._activeAnimatables[index];
  25856. }
  25857. }
  25858. return null;
  25859. };
  25860. /**
  25861. * Gets all animatables associated with a given target
  25862. * @param target defines the target to look animatables for
  25863. * @returns an array of Animatables
  25864. */
  25865. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25866. var result = [];
  25867. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25868. if (this._activeAnimatables[index].target === target) {
  25869. result.push(this._activeAnimatables[index]);
  25870. }
  25871. }
  25872. return result;
  25873. };
  25874. Object.defineProperty(Scene.prototype, "animatables", {
  25875. /**
  25876. * Gets all animatable attached to the scene
  25877. */
  25878. get: function () {
  25879. return this._activeAnimatables;
  25880. },
  25881. enumerable: true,
  25882. configurable: true
  25883. });
  25884. /**
  25885. * Will stop the animation of the given target
  25886. * @param target - the target
  25887. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25888. */
  25889. Scene.prototype.stopAnimation = function (target, animationName) {
  25890. var animatables = this.getAllAnimatablesByTarget(target);
  25891. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25892. var animatable = animatables_1[_i];
  25893. animatable.stop(animationName);
  25894. }
  25895. };
  25896. /**
  25897. * Stops and removes all animations that have been applied to the scene
  25898. */
  25899. Scene.prototype.stopAllAnimations = function () {
  25900. if (this._activeAnimatables) {
  25901. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25902. this._activeAnimatables[i].stop();
  25903. }
  25904. this._activeAnimatables = [];
  25905. }
  25906. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25907. var group = _a[_i];
  25908. group.stop();
  25909. }
  25910. };
  25911. Scene.prototype._animate = function () {
  25912. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25913. return;
  25914. }
  25915. // Getting time
  25916. var now = BABYLON.Tools.Now;
  25917. if (!this._animationTimeLast) {
  25918. if (this._pendingData.length > 0) {
  25919. return;
  25920. }
  25921. this._animationTimeLast = now;
  25922. }
  25923. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25924. this._animationTime += deltaTime;
  25925. this._animationTimeLast = now;
  25926. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25927. this._activeAnimatables[index]._animate(this._animationTime);
  25928. }
  25929. // Late animation bindings
  25930. this._processLateAnimationBindings();
  25931. };
  25932. /** @hidden */
  25933. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25934. var target = runtimeAnimation.target;
  25935. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25936. if (!target._lateAnimationHolders) {
  25937. target._lateAnimationHolders = {};
  25938. }
  25939. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25940. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25941. totalWeight: 0,
  25942. animations: [],
  25943. originalValue: originalValue
  25944. };
  25945. }
  25946. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25947. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25948. };
  25949. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25950. var normalizer = 1.0;
  25951. var finalPosition = BABYLON.Tmp.Vector3[0];
  25952. var finalScaling = BABYLON.Tmp.Vector3[1];
  25953. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25954. var startIndex = 0;
  25955. var originalAnimation = holder.animations[0];
  25956. var originalValue = holder.originalValue;
  25957. var scale = 1;
  25958. if (holder.totalWeight < 1.0) {
  25959. // We need to mix the original value in
  25960. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25961. scale = 1.0 - holder.totalWeight;
  25962. }
  25963. else {
  25964. startIndex = 1;
  25965. // We need to normalize the weights
  25966. normalizer = holder.totalWeight;
  25967. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25968. scale = originalAnimation.weight / normalizer;
  25969. if (scale == 1) {
  25970. return originalAnimation.currentValue;
  25971. }
  25972. }
  25973. finalScaling.scaleInPlace(scale);
  25974. finalPosition.scaleInPlace(scale);
  25975. finalQuaternion.scaleInPlace(scale);
  25976. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25977. var runtimeAnimation = holder.animations[animIndex];
  25978. var scale = runtimeAnimation.weight / normalizer;
  25979. var currentPosition = BABYLON.Tmp.Vector3[2];
  25980. var currentScaling = BABYLON.Tmp.Vector3[3];
  25981. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25982. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25983. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25984. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25985. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25986. }
  25987. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25988. return originalAnimation._workValue;
  25989. };
  25990. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25991. var originalAnimation = holder.animations[0];
  25992. var originalValue = holder.originalValue;
  25993. if (holder.animations.length === 1) {
  25994. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25995. }
  25996. var normalizer = 1.0;
  25997. var quaternions;
  25998. var weights;
  25999. if (holder.totalWeight < 1.0) {
  26000. var scale = 1.0 - holder.totalWeight;
  26001. quaternions = [];
  26002. weights = [];
  26003. quaternions.push(originalValue);
  26004. weights.push(scale);
  26005. }
  26006. else {
  26007. if (holder.animations.length === 2) { // Slerp as soon as we can
  26008. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26009. }
  26010. quaternions = [];
  26011. weights = [];
  26012. normalizer = holder.totalWeight;
  26013. }
  26014. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26015. var runtimeAnimation = holder.animations[animIndex];
  26016. quaternions.push(runtimeAnimation.currentValue);
  26017. weights.push(runtimeAnimation.weight / normalizer);
  26018. }
  26019. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26020. var cumulativeAmount = 0;
  26021. var cumulativeQuaternion = null;
  26022. for (var index = 0; index < quaternions.length;) {
  26023. if (!cumulativeQuaternion) {
  26024. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26025. cumulativeAmount = weights[index] + weights[index + 1];
  26026. index += 2;
  26027. continue;
  26028. }
  26029. cumulativeAmount += weights[index];
  26030. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26031. index++;
  26032. }
  26033. return cumulativeQuaternion;
  26034. };
  26035. Scene.prototype._processLateAnimationBindings = function () {
  26036. if (!this._registeredForLateAnimationBindings.length) {
  26037. return;
  26038. }
  26039. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26040. var target = this._registeredForLateAnimationBindings.data[index];
  26041. for (var path in target._lateAnimationHolders) {
  26042. var holder = target._lateAnimationHolders[path];
  26043. var originalAnimation = holder.animations[0];
  26044. var originalValue = holder.originalValue;
  26045. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26046. var finalValue = void 0;
  26047. if (matrixDecomposeMode) {
  26048. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26049. }
  26050. else {
  26051. var quaternionMode = originalValue.w !== undefined;
  26052. if (quaternionMode) {
  26053. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26054. }
  26055. else {
  26056. var startIndex = 0;
  26057. var normalizer = 1.0;
  26058. if (holder.totalWeight < 1.0) {
  26059. // We need to mix the original value in
  26060. if (originalValue.scale) {
  26061. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26062. }
  26063. else {
  26064. finalValue = originalValue * (1.0 - holder.totalWeight);
  26065. }
  26066. }
  26067. else {
  26068. // We need to normalize the weights
  26069. normalizer = holder.totalWeight;
  26070. var scale_1 = originalAnimation.weight / normalizer;
  26071. if (scale_1 !== 1) {
  26072. if (originalAnimation.currentValue.scale) {
  26073. finalValue = originalAnimation.currentValue.scale(scale_1);
  26074. }
  26075. else {
  26076. finalValue = originalAnimation.currentValue * scale_1;
  26077. }
  26078. }
  26079. else {
  26080. finalValue = originalAnimation.currentValue;
  26081. }
  26082. startIndex = 1;
  26083. }
  26084. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26085. var runtimeAnimation = holder.animations[animIndex];
  26086. var scale = runtimeAnimation.weight / normalizer;
  26087. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26088. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26089. }
  26090. else {
  26091. finalValue += runtimeAnimation.currentValue * scale;
  26092. }
  26093. }
  26094. }
  26095. }
  26096. target[path] = finalValue;
  26097. }
  26098. target._lateAnimationHolders = {};
  26099. }
  26100. this._registeredForLateAnimationBindings.reset();
  26101. };
  26102. // Matrix
  26103. /** @hidden */
  26104. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26105. this._useAlternateCameraConfiguration = active;
  26106. };
  26107. /**
  26108. * Gets the current view matrix
  26109. * @returns a Matrix
  26110. */
  26111. Scene.prototype.getViewMatrix = function () {
  26112. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26113. };
  26114. /**
  26115. * Gets the current projection matrix
  26116. * @returns a Matrix
  26117. */
  26118. Scene.prototype.getProjectionMatrix = function () {
  26119. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26120. };
  26121. /**
  26122. * Gets the current transform matrix
  26123. * @returns a Matrix made of View * Projection
  26124. */
  26125. Scene.prototype.getTransformMatrix = function () {
  26126. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26127. };
  26128. /**
  26129. * Sets the current transform matrix
  26130. * @param view defines the View matrix to use
  26131. * @param projection defines the Projection matrix to use
  26132. */
  26133. Scene.prototype.setTransformMatrix = function (view, projection) {
  26134. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26135. return;
  26136. }
  26137. this._viewUpdateFlag = view.updateFlag;
  26138. this._projectionUpdateFlag = projection.updateFlag;
  26139. this._viewMatrix = view;
  26140. this._projectionMatrix = projection;
  26141. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26142. // Update frustum
  26143. if (!this._frustumPlanes) {
  26144. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26145. }
  26146. else {
  26147. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26148. }
  26149. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26150. var otherCamera = this.activeCamera._alternateCamera;
  26151. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26152. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26153. }
  26154. if (this._sceneUbo.useUbo) {
  26155. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26156. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26157. this._sceneUbo.update();
  26158. }
  26159. };
  26160. /** @hidden */
  26161. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26162. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26163. return;
  26164. }
  26165. this._alternateViewUpdateFlag = view.updateFlag;
  26166. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26167. this._alternateViewMatrix = view;
  26168. this._alternateProjectionMatrix = projection;
  26169. if (!this._alternateTransformMatrix) {
  26170. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26171. }
  26172. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26173. if (!this._alternateSceneUbo) {
  26174. this._createAlternateUbo();
  26175. }
  26176. if (this._alternateSceneUbo.useUbo) {
  26177. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26178. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26179. this._alternateSceneUbo.update();
  26180. }
  26181. };
  26182. /**
  26183. * Gets the uniform buffer used to store scene data
  26184. * @returns a UniformBuffer
  26185. */
  26186. Scene.prototype.getSceneUniformBuffer = function () {
  26187. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26188. };
  26189. /**
  26190. * Gets an unique (relatively to the current scene) Id
  26191. * @returns an unique number for the scene
  26192. */
  26193. Scene.prototype.getUniqueId = function () {
  26194. var result = Scene._uniqueIdCounter;
  26195. Scene._uniqueIdCounter++;
  26196. return result;
  26197. };
  26198. /**
  26199. * Add a mesh to the list of scene's meshes
  26200. * @param newMesh defines the mesh to add
  26201. * @param recursive if all child meshes should also be added to the scene
  26202. */
  26203. Scene.prototype.addMesh = function (newMesh, recursive) {
  26204. var _this = this;
  26205. if (recursive === void 0) { recursive = false; }
  26206. this.meshes.push(newMesh);
  26207. //notify the collision coordinator
  26208. if (this.collisionCoordinator) {
  26209. this.collisionCoordinator.onMeshAdded(newMesh);
  26210. }
  26211. newMesh._resyncLightSources();
  26212. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26213. if (recursive) {
  26214. newMesh.getChildMeshes().forEach(function (m) {
  26215. _this.addMesh(m);
  26216. });
  26217. }
  26218. };
  26219. /**
  26220. * Remove a mesh for the list of scene's meshes
  26221. * @param toRemove defines the mesh to remove
  26222. * @param recursive if all child meshes should also be removed from the scene
  26223. * @returns the index where the mesh was in the mesh list
  26224. */
  26225. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26226. var _this = this;
  26227. if (recursive === void 0) { recursive = false; }
  26228. var index = this.meshes.indexOf(toRemove);
  26229. if (index !== -1) {
  26230. // Remove from the scene if mesh found
  26231. this.meshes.splice(index, 1);
  26232. }
  26233. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26234. if (recursive) {
  26235. toRemove.getChildMeshes().forEach(function (m) {
  26236. _this.removeMesh(m);
  26237. });
  26238. }
  26239. return index;
  26240. };
  26241. /**
  26242. * Add a transform node to the list of scene's transform nodes
  26243. * @param newTransformNode defines the transform node to add
  26244. */
  26245. Scene.prototype.addTransformNode = function (newTransformNode) {
  26246. this.transformNodes.push(newTransformNode);
  26247. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26248. };
  26249. /**
  26250. * Remove a transform node for the list of scene's transform nodes
  26251. * @param toRemove defines the transform node to remove
  26252. * @returns the index where the transform node was in the transform node list
  26253. */
  26254. Scene.prototype.removeTransformNode = function (toRemove) {
  26255. var index = this.transformNodes.indexOf(toRemove);
  26256. if (index !== -1) {
  26257. // Remove from the scene if found
  26258. this.transformNodes.splice(index, 1);
  26259. }
  26260. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26261. return index;
  26262. };
  26263. /**
  26264. * Remove a skeleton for the list of scene's skeletons
  26265. * @param toRemove defines the skeleton to remove
  26266. * @returns the index where the skeleton was in the skeleton list
  26267. */
  26268. Scene.prototype.removeSkeleton = function (toRemove) {
  26269. var index = this.skeletons.indexOf(toRemove);
  26270. if (index !== -1) {
  26271. // Remove from the scene if found
  26272. this.skeletons.splice(index, 1);
  26273. }
  26274. return index;
  26275. };
  26276. /**
  26277. * Remove a morph target for the list of scene's morph targets
  26278. * @param toRemove defines the morph target to remove
  26279. * @returns the index where the morph target was in the morph target list
  26280. */
  26281. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26282. var index = this.morphTargetManagers.indexOf(toRemove);
  26283. if (index !== -1) {
  26284. // Remove from the scene if found
  26285. this.morphTargetManagers.splice(index, 1);
  26286. }
  26287. return index;
  26288. };
  26289. /**
  26290. * Remove a light for the list of scene's lights
  26291. * @param toRemove defines the light to remove
  26292. * @returns the index where the light was in the light list
  26293. */
  26294. Scene.prototype.removeLight = function (toRemove) {
  26295. var index = this.lights.indexOf(toRemove);
  26296. if (index !== -1) {
  26297. // Remove from meshes
  26298. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26299. var mesh = _a[_i];
  26300. mesh._removeLightSource(toRemove);
  26301. }
  26302. // Remove from the scene if mesh found
  26303. this.lights.splice(index, 1);
  26304. this.sortLightsByPriority();
  26305. }
  26306. this.onLightRemovedObservable.notifyObservers(toRemove);
  26307. return index;
  26308. };
  26309. /**
  26310. * Remove a camera for the list of scene's cameras
  26311. * @param toRemove defines the camera to remove
  26312. * @returns the index where the camera was in the camera list
  26313. */
  26314. Scene.prototype.removeCamera = function (toRemove) {
  26315. var index = this.cameras.indexOf(toRemove);
  26316. if (index !== -1) {
  26317. // Remove from the scene if mesh found
  26318. this.cameras.splice(index, 1);
  26319. }
  26320. // Remove from activeCameras
  26321. var index2 = this.activeCameras.indexOf(toRemove);
  26322. if (index2 !== -1) {
  26323. // Remove from the scene if mesh found
  26324. this.activeCameras.splice(index2, 1);
  26325. }
  26326. // Reset the activeCamera
  26327. if (this.activeCamera === toRemove) {
  26328. if (this.cameras.length > 0) {
  26329. this.activeCamera = this.cameras[0];
  26330. }
  26331. else {
  26332. this.activeCamera = null;
  26333. }
  26334. }
  26335. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26336. return index;
  26337. };
  26338. /**
  26339. * Remove a particle system for the list of scene's particle systems
  26340. * @param toRemove defines the particle system to remove
  26341. * @returns the index where the particle system was in the particle system list
  26342. */
  26343. Scene.prototype.removeParticleSystem = function (toRemove) {
  26344. var index = this.particleSystems.indexOf(toRemove);
  26345. if (index !== -1) {
  26346. this.particleSystems.splice(index, 1);
  26347. }
  26348. return index;
  26349. };
  26350. /**
  26351. * Remove a animation for the list of scene's animations
  26352. * @param toRemove defines the animation to remove
  26353. * @returns the index where the animation was in the animation list
  26354. */
  26355. Scene.prototype.removeAnimation = function (toRemove) {
  26356. var index = this.animations.indexOf(toRemove);
  26357. if (index !== -1) {
  26358. this.animations.splice(index, 1);
  26359. }
  26360. return index;
  26361. };
  26362. /**
  26363. * Removes the given animation group from this scene.
  26364. * @param toRemove The animation group to remove
  26365. * @returns The index of the removed animation group
  26366. */
  26367. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26368. var index = this.animationGroups.indexOf(toRemove);
  26369. if (index !== -1) {
  26370. this.animationGroups.splice(index, 1);
  26371. }
  26372. return index;
  26373. };
  26374. /**
  26375. * Removes the given multi-material from this scene.
  26376. * @param toRemove The multi-material to remove
  26377. * @returns The index of the removed multi-material
  26378. */
  26379. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26380. var index = this.multiMaterials.indexOf(toRemove);
  26381. if (index !== -1) {
  26382. this.multiMaterials.splice(index, 1);
  26383. }
  26384. return index;
  26385. };
  26386. /**
  26387. * Removes the given material from this scene.
  26388. * @param toRemove The material to remove
  26389. * @returns The index of the removed material
  26390. */
  26391. Scene.prototype.removeMaterial = function (toRemove) {
  26392. var index = this.materials.indexOf(toRemove);
  26393. if (index !== -1) {
  26394. this.materials.splice(index, 1);
  26395. }
  26396. return index;
  26397. };
  26398. /**
  26399. * Removes the given lens flare system from this scene.
  26400. * @param toRemove The lens flare system to remove
  26401. * @returns The index of the removed lens flare system
  26402. */
  26403. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26404. var index = this.lensFlareSystems.indexOf(toRemove);
  26405. if (index !== -1) {
  26406. this.lensFlareSystems.splice(index, 1);
  26407. }
  26408. return index;
  26409. };
  26410. /**
  26411. * Removes the given action manager from this scene.
  26412. * @param toRemove The action manager to remove
  26413. * @returns The index of the removed action manager
  26414. */
  26415. Scene.prototype.removeActionManager = function (toRemove) {
  26416. var index = this._actionManagers.indexOf(toRemove);
  26417. if (index !== -1) {
  26418. this._actionManagers.splice(index, 1);
  26419. }
  26420. return index;
  26421. };
  26422. /**
  26423. * Removes the given effect layer from this scene.
  26424. * @param toRemove defines the effect layer to remove
  26425. * @returns the index of the removed effect layer
  26426. */
  26427. Scene.prototype.removeEffectLayer = function (toRemove) {
  26428. var index = this.effectLayers.indexOf(toRemove);
  26429. if (index !== -1) {
  26430. this.effectLayers.splice(index, 1);
  26431. }
  26432. return index;
  26433. };
  26434. /**
  26435. * Removes the given texture from this scene.
  26436. * @param toRemove The texture to remove
  26437. * @returns The index of the removed texture
  26438. */
  26439. Scene.prototype.removeTexture = function (toRemove) {
  26440. var index = this.textures.indexOf(toRemove);
  26441. if (index !== -1) {
  26442. this.textures.splice(index, 1);
  26443. }
  26444. return index;
  26445. };
  26446. /**
  26447. * Adds the given light to this scene
  26448. * @param newLight The light to add
  26449. */
  26450. Scene.prototype.addLight = function (newLight) {
  26451. this.lights.push(newLight);
  26452. this.sortLightsByPriority();
  26453. // Add light to all meshes (To support if the light is removed and then readded)
  26454. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26455. var mesh = _a[_i];
  26456. if (mesh._lightSources.indexOf(newLight) === -1) {
  26457. mesh._lightSources.push(newLight);
  26458. mesh._resyncLightSources();
  26459. }
  26460. }
  26461. this.onNewLightAddedObservable.notifyObservers(newLight);
  26462. };
  26463. /**
  26464. * Sorts the list list based on light priorities
  26465. */
  26466. Scene.prototype.sortLightsByPriority = function () {
  26467. if (this.requireLightSorting) {
  26468. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26469. }
  26470. };
  26471. /**
  26472. * Adds the given camera to this scene
  26473. * @param newCamera The camera to add
  26474. */
  26475. Scene.prototype.addCamera = function (newCamera) {
  26476. this.cameras.push(newCamera);
  26477. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26478. };
  26479. /**
  26480. * Adds the given skeleton to this scene
  26481. * @param newSkeleton The skeleton to add
  26482. */
  26483. Scene.prototype.addSkeleton = function (newSkeleton) {
  26484. this.skeletons.push(newSkeleton);
  26485. };
  26486. /**
  26487. * Adds the given particle system to this scene
  26488. * @param newParticleSystem The particle system to add
  26489. */
  26490. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26491. this.particleSystems.push(newParticleSystem);
  26492. };
  26493. /**
  26494. * Adds the given animation to this scene
  26495. * @param newAnimation The animation to add
  26496. */
  26497. Scene.prototype.addAnimation = function (newAnimation) {
  26498. this.animations.push(newAnimation);
  26499. };
  26500. /**
  26501. * Adds the given animation group to this scene.
  26502. * @param newAnimationGroup The animation group to add
  26503. */
  26504. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26505. this.animationGroups.push(newAnimationGroup);
  26506. };
  26507. /**
  26508. * Adds the given multi-material to this scene
  26509. * @param newMultiMaterial The multi-material to add
  26510. */
  26511. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26512. this.multiMaterials.push(newMultiMaterial);
  26513. };
  26514. /**
  26515. * Adds the given material to this scene
  26516. * @param newMaterial The material to add
  26517. */
  26518. Scene.prototype.addMaterial = function (newMaterial) {
  26519. this.materials.push(newMaterial);
  26520. };
  26521. /**
  26522. * Adds the given morph target to this scene
  26523. * @param newMorphTargetManager The morph target to add
  26524. */
  26525. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26526. this.morphTargetManagers.push(newMorphTargetManager);
  26527. };
  26528. /**
  26529. * Adds the given geometry to this scene
  26530. * @param newGeometry The geometry to add
  26531. */
  26532. Scene.prototype.addGeometry = function (newGeometry) {
  26533. this._geometries.push(newGeometry);
  26534. };
  26535. /**
  26536. * Adds the given lens flare system to this scene
  26537. * @param newLensFlareSystem The lens flare system to add
  26538. */
  26539. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26540. this.lensFlareSystems.push(newLensFlareSystem);
  26541. };
  26542. /**
  26543. * Adds the given effect layer to this scene
  26544. * @param newEffectLayer defines the effect layer to add
  26545. */
  26546. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26547. this.effectLayers.push(newEffectLayer);
  26548. };
  26549. /**
  26550. * Adds the given action manager to this scene
  26551. * @param newActionManager The action manager to add
  26552. */
  26553. Scene.prototype.addActionManager = function (newActionManager) {
  26554. this._actionManagers.push(newActionManager);
  26555. };
  26556. /**
  26557. * Adds the given texture to this scene.
  26558. * @param newTexture The texture to add
  26559. */
  26560. Scene.prototype.addTexture = function (newTexture) {
  26561. this.textures.push(newTexture);
  26562. };
  26563. /**
  26564. * Switch active camera
  26565. * @param newCamera defines the new active camera
  26566. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26567. */
  26568. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26569. if (attachControl === void 0) { attachControl = true; }
  26570. var canvas = this._engine.getRenderingCanvas();
  26571. if (!canvas) {
  26572. return;
  26573. }
  26574. if (this.activeCamera) {
  26575. this.activeCamera.detachControl(canvas);
  26576. }
  26577. this.activeCamera = newCamera;
  26578. if (attachControl) {
  26579. newCamera.attachControl(canvas);
  26580. }
  26581. };
  26582. /**
  26583. * sets the active camera of the scene using its ID
  26584. * @param id defines the camera's ID
  26585. * @return the new active camera or null if none found.
  26586. */
  26587. Scene.prototype.setActiveCameraByID = function (id) {
  26588. var camera = this.getCameraByID(id);
  26589. if (camera) {
  26590. this.activeCamera = camera;
  26591. return camera;
  26592. }
  26593. return null;
  26594. };
  26595. /**
  26596. * sets the active camera of the scene using its name
  26597. * @param name defines the camera's name
  26598. * @returns the new active camera or null if none found.
  26599. */
  26600. Scene.prototype.setActiveCameraByName = function (name) {
  26601. var camera = this.getCameraByName(name);
  26602. if (camera) {
  26603. this.activeCamera = camera;
  26604. return camera;
  26605. }
  26606. return null;
  26607. };
  26608. /**
  26609. * get an animation group using its name
  26610. * @param name defines the material's name
  26611. * @return the animation group or null if none found.
  26612. */
  26613. Scene.prototype.getAnimationGroupByName = function (name) {
  26614. for (var index = 0; index < this.animationGroups.length; index++) {
  26615. if (this.animationGroups[index].name === name) {
  26616. return this.animationGroups[index];
  26617. }
  26618. }
  26619. return null;
  26620. };
  26621. /**
  26622. * get a material using its id
  26623. * @param id defines the material's ID
  26624. * @return the material or null if none found.
  26625. */
  26626. Scene.prototype.getMaterialByID = function (id) {
  26627. for (var index = 0; index < this.materials.length; index++) {
  26628. if (this.materials[index].id === id) {
  26629. return this.materials[index];
  26630. }
  26631. }
  26632. return null;
  26633. };
  26634. /**
  26635. * Gets a material using its name
  26636. * @param name defines the material's name
  26637. * @return the material or null if none found.
  26638. */
  26639. Scene.prototype.getMaterialByName = function (name) {
  26640. for (var index = 0; index < this.materials.length; index++) {
  26641. if (this.materials[index].name === name) {
  26642. return this.materials[index];
  26643. }
  26644. }
  26645. return null;
  26646. };
  26647. /**
  26648. * Gets a lens flare system using its name
  26649. * @param name defines the name to look for
  26650. * @returns the lens flare system or null if not found
  26651. */
  26652. Scene.prototype.getLensFlareSystemByName = function (name) {
  26653. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26654. if (this.lensFlareSystems[index].name === name) {
  26655. return this.lensFlareSystems[index];
  26656. }
  26657. }
  26658. return null;
  26659. };
  26660. /**
  26661. * Gets a lens flare system using its id
  26662. * @param id defines the id to look for
  26663. * @returns the lens flare system or null if not found
  26664. */
  26665. Scene.prototype.getLensFlareSystemByID = function (id) {
  26666. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26667. if (this.lensFlareSystems[index].id === id) {
  26668. return this.lensFlareSystems[index];
  26669. }
  26670. }
  26671. return null;
  26672. };
  26673. /**
  26674. * Gets a camera using its id
  26675. * @param id defines the id to look for
  26676. * @returns the camera or null if not found
  26677. */
  26678. Scene.prototype.getCameraByID = function (id) {
  26679. for (var index = 0; index < this.cameras.length; index++) {
  26680. if (this.cameras[index].id === id) {
  26681. return this.cameras[index];
  26682. }
  26683. }
  26684. return null;
  26685. };
  26686. /**
  26687. * Gets a camera using its unique id
  26688. * @param uniqueId defines the unique id to look for
  26689. * @returns the camera or null if not found
  26690. */
  26691. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26692. for (var index = 0; index < this.cameras.length; index++) {
  26693. if (this.cameras[index].uniqueId === uniqueId) {
  26694. return this.cameras[index];
  26695. }
  26696. }
  26697. return null;
  26698. };
  26699. /**
  26700. * Gets a camera using its name
  26701. * @param name defines the camera's name
  26702. * @return the camera or null if none found.
  26703. */
  26704. Scene.prototype.getCameraByName = function (name) {
  26705. for (var index = 0; index < this.cameras.length; index++) {
  26706. if (this.cameras[index].name === name) {
  26707. return this.cameras[index];
  26708. }
  26709. }
  26710. return null;
  26711. };
  26712. /**
  26713. * Gets a bone using its id
  26714. * @param id defines the bone's id
  26715. * @return the bone or null if not found
  26716. */
  26717. Scene.prototype.getBoneByID = function (id) {
  26718. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26719. var skeleton = this.skeletons[skeletonIndex];
  26720. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26721. if (skeleton.bones[boneIndex].id === id) {
  26722. return skeleton.bones[boneIndex];
  26723. }
  26724. }
  26725. }
  26726. return null;
  26727. };
  26728. /**
  26729. * Gets a bone using its id
  26730. * @param name defines the bone's name
  26731. * @return the bone or null if not found
  26732. */
  26733. Scene.prototype.getBoneByName = function (name) {
  26734. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26735. var skeleton = this.skeletons[skeletonIndex];
  26736. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26737. if (skeleton.bones[boneIndex].name === name) {
  26738. return skeleton.bones[boneIndex];
  26739. }
  26740. }
  26741. }
  26742. return null;
  26743. };
  26744. /**
  26745. * Gets a light node using its name
  26746. * @param name defines the the light's name
  26747. * @return the light or null if none found.
  26748. */
  26749. Scene.prototype.getLightByName = function (name) {
  26750. for (var index = 0; index < this.lights.length; index++) {
  26751. if (this.lights[index].name === name) {
  26752. return this.lights[index];
  26753. }
  26754. }
  26755. return null;
  26756. };
  26757. /**
  26758. * Gets a light node using its id
  26759. * @param id defines the light's id
  26760. * @return the light or null if none found.
  26761. */
  26762. Scene.prototype.getLightByID = function (id) {
  26763. for (var index = 0; index < this.lights.length; index++) {
  26764. if (this.lights[index].id === id) {
  26765. return this.lights[index];
  26766. }
  26767. }
  26768. return null;
  26769. };
  26770. /**
  26771. * Gets a light node using its scene-generated unique ID
  26772. * @param uniqueId defines the light's unique id
  26773. * @return the light or null if none found.
  26774. */
  26775. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26776. for (var index = 0; index < this.lights.length; index++) {
  26777. if (this.lights[index].uniqueId === uniqueId) {
  26778. return this.lights[index];
  26779. }
  26780. }
  26781. return null;
  26782. };
  26783. /**
  26784. * Gets a particle system by id
  26785. * @param id defines the particle system id
  26786. * @return the corresponding system or null if none found
  26787. */
  26788. Scene.prototype.getParticleSystemByID = function (id) {
  26789. for (var index = 0; index < this.particleSystems.length; index++) {
  26790. if (this.particleSystems[index].id === id) {
  26791. return this.particleSystems[index];
  26792. }
  26793. }
  26794. return null;
  26795. };
  26796. /**
  26797. * Gets a geometry using its ID
  26798. * @param id defines the geometry's id
  26799. * @return the geometry or null if none found.
  26800. */
  26801. Scene.prototype.getGeometryByID = function (id) {
  26802. for (var index = 0; index < this._geometries.length; index++) {
  26803. if (this._geometries[index].id === id) {
  26804. return this._geometries[index];
  26805. }
  26806. }
  26807. return null;
  26808. };
  26809. /**
  26810. * Add a new geometry to this scene
  26811. * @param geometry defines the geometry to be added to the scene.
  26812. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26813. * @return a boolean defining if the geometry was added or not
  26814. */
  26815. Scene.prototype.pushGeometry = function (geometry, force) {
  26816. if (!force && this.getGeometryByID(geometry.id)) {
  26817. return false;
  26818. }
  26819. this._geometries.push(geometry);
  26820. //notify the collision coordinator
  26821. if (this.collisionCoordinator) {
  26822. this.collisionCoordinator.onGeometryAdded(geometry);
  26823. }
  26824. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26825. return true;
  26826. };
  26827. /**
  26828. * Removes an existing geometry
  26829. * @param geometry defines the geometry to be removed from the scene
  26830. * @return a boolean defining if the geometry was removed or not
  26831. */
  26832. Scene.prototype.removeGeometry = function (geometry) {
  26833. var index = this._geometries.indexOf(geometry);
  26834. if (index > -1) {
  26835. this._geometries.splice(index, 1);
  26836. //notify the collision coordinator
  26837. if (this.collisionCoordinator) {
  26838. this.collisionCoordinator.onGeometryDeleted(geometry);
  26839. }
  26840. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26841. return true;
  26842. }
  26843. return false;
  26844. };
  26845. /**
  26846. * Gets the list of geometries attached to the scene
  26847. * @returns an array of Geometry
  26848. */
  26849. Scene.prototype.getGeometries = function () {
  26850. return this._geometries;
  26851. };
  26852. /**
  26853. * Gets the first added mesh found of a given ID
  26854. * @param id defines the id to search for
  26855. * @return the mesh found or null if not found at all
  26856. */
  26857. Scene.prototype.getMeshByID = function (id) {
  26858. for (var index = 0; index < this.meshes.length; index++) {
  26859. if (this.meshes[index].id === id) {
  26860. return this.meshes[index];
  26861. }
  26862. }
  26863. return null;
  26864. };
  26865. /**
  26866. * Gets a list of meshes using their id
  26867. * @param id defines the id to search for
  26868. * @returns a list of meshes
  26869. */
  26870. Scene.prototype.getMeshesByID = function (id) {
  26871. return this.meshes.filter(function (m) {
  26872. return m.id === id;
  26873. });
  26874. };
  26875. /**
  26876. * Gets the first added transform node found of a given ID
  26877. * @param id defines the id to search for
  26878. * @return the found transform node or null if not found at all.
  26879. */
  26880. Scene.prototype.getTransformNodeByID = function (id) {
  26881. for (var index = 0; index < this.transformNodes.length; index++) {
  26882. if (this.transformNodes[index].id === id) {
  26883. return this.transformNodes[index];
  26884. }
  26885. }
  26886. return null;
  26887. };
  26888. /**
  26889. * Gets a list of transform nodes using their id
  26890. * @param id defines the id to search for
  26891. * @returns a list of transform nodes
  26892. */
  26893. Scene.prototype.getTransformNodesByID = function (id) {
  26894. return this.transformNodes.filter(function (m) {
  26895. return m.id === id;
  26896. });
  26897. };
  26898. /**
  26899. * Gets a mesh with its auto-generated unique id
  26900. * @param uniqueId defines the unique id to search for
  26901. * @return the found mesh or null if not found at all.
  26902. */
  26903. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26904. for (var index = 0; index < this.meshes.length; index++) {
  26905. if (this.meshes[index].uniqueId === uniqueId) {
  26906. return this.meshes[index];
  26907. }
  26908. }
  26909. return null;
  26910. };
  26911. /**
  26912. * Gets a the last added mesh using a given id
  26913. * @param id defines the id to search for
  26914. * @return the found mesh or null if not found at all.
  26915. */
  26916. Scene.prototype.getLastMeshByID = function (id) {
  26917. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26918. if (this.meshes[index].id === id) {
  26919. return this.meshes[index];
  26920. }
  26921. }
  26922. return null;
  26923. };
  26924. /**
  26925. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26926. * @param id defines the id to search for
  26927. * @return the found node or null if not found at all
  26928. */
  26929. Scene.prototype.getLastEntryByID = function (id) {
  26930. var index;
  26931. for (index = this.meshes.length - 1; index >= 0; index--) {
  26932. if (this.meshes[index].id === id) {
  26933. return this.meshes[index];
  26934. }
  26935. }
  26936. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26937. if (this.transformNodes[index].id === id) {
  26938. return this.transformNodes[index];
  26939. }
  26940. }
  26941. for (index = this.cameras.length - 1; index >= 0; index--) {
  26942. if (this.cameras[index].id === id) {
  26943. return this.cameras[index];
  26944. }
  26945. }
  26946. for (index = this.lights.length - 1; index >= 0; index--) {
  26947. if (this.lights[index].id === id) {
  26948. return this.lights[index];
  26949. }
  26950. }
  26951. return null;
  26952. };
  26953. /**
  26954. * Gets a node (Mesh, Camera, Light) using a given id
  26955. * @param id defines the id to search for
  26956. * @return the found node or null if not found at all
  26957. */
  26958. Scene.prototype.getNodeByID = function (id) {
  26959. var mesh = this.getMeshByID(id);
  26960. if (mesh) {
  26961. return mesh;
  26962. }
  26963. var light = this.getLightByID(id);
  26964. if (light) {
  26965. return light;
  26966. }
  26967. var camera = this.getCameraByID(id);
  26968. if (camera) {
  26969. return camera;
  26970. }
  26971. var bone = this.getBoneByID(id);
  26972. return bone;
  26973. };
  26974. /**
  26975. * Gets a node (Mesh, Camera, Light) using a given name
  26976. * @param name defines the name to search for
  26977. * @return the found node or null if not found at all.
  26978. */
  26979. Scene.prototype.getNodeByName = function (name) {
  26980. var mesh = this.getMeshByName(name);
  26981. if (mesh) {
  26982. return mesh;
  26983. }
  26984. var light = this.getLightByName(name);
  26985. if (light) {
  26986. return light;
  26987. }
  26988. var camera = this.getCameraByName(name);
  26989. if (camera) {
  26990. return camera;
  26991. }
  26992. var bone = this.getBoneByName(name);
  26993. return bone;
  26994. };
  26995. /**
  26996. * Gets a mesh using a given name
  26997. * @param name defines the name to search for
  26998. * @return the found mesh or null if not found at all.
  26999. */
  27000. Scene.prototype.getMeshByName = function (name) {
  27001. for (var index = 0; index < this.meshes.length; index++) {
  27002. if (this.meshes[index].name === name) {
  27003. return this.meshes[index];
  27004. }
  27005. }
  27006. return null;
  27007. };
  27008. /**
  27009. * Gets a transform node using a given name
  27010. * @param name defines the name to search for
  27011. * @return the found transform node or null if not found at all.
  27012. */
  27013. Scene.prototype.getTransformNodeByName = function (name) {
  27014. for (var index = 0; index < this.transformNodes.length; index++) {
  27015. if (this.transformNodes[index].name === name) {
  27016. return this.transformNodes[index];
  27017. }
  27018. }
  27019. return null;
  27020. };
  27021. /**
  27022. * Gets a sound using a given name
  27023. * @param name defines the name to search for
  27024. * @return the found sound or null if not found at all.
  27025. */
  27026. Scene.prototype.getSoundByName = function (name) {
  27027. var index;
  27028. if (BABYLON.AudioEngine) {
  27029. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27030. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27031. return this.mainSoundTrack.soundCollection[index];
  27032. }
  27033. }
  27034. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27035. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27036. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27037. return this.soundTracks[sdIndex].soundCollection[index];
  27038. }
  27039. }
  27040. }
  27041. }
  27042. return null;
  27043. };
  27044. /**
  27045. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27046. * @param id defines the id to search for
  27047. * @return the found skeleton or null if not found at all.
  27048. */
  27049. Scene.prototype.getLastSkeletonByID = function (id) {
  27050. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27051. if (this.skeletons[index].id === id) {
  27052. return this.skeletons[index];
  27053. }
  27054. }
  27055. return null;
  27056. };
  27057. /**
  27058. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27059. * @param id defines the id to search for
  27060. * @return the found skeleton or null if not found at all.
  27061. */
  27062. Scene.prototype.getSkeletonById = function (id) {
  27063. for (var index = 0; index < this.skeletons.length; index++) {
  27064. if (this.skeletons[index].id === id) {
  27065. return this.skeletons[index];
  27066. }
  27067. }
  27068. return null;
  27069. };
  27070. /**
  27071. * Gets a skeleton using a given name
  27072. * @param name defines the name to search for
  27073. * @return the found skeleton or null if not found at all.
  27074. */
  27075. Scene.prototype.getSkeletonByName = function (name) {
  27076. for (var index = 0; index < this.skeletons.length; index++) {
  27077. if (this.skeletons[index].name === name) {
  27078. return this.skeletons[index];
  27079. }
  27080. }
  27081. return null;
  27082. };
  27083. /**
  27084. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27085. * @param id defines the id to search for
  27086. * @return the found morph target manager or null if not found at all.
  27087. */
  27088. Scene.prototype.getMorphTargetManagerById = function (id) {
  27089. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27090. if (this.morphTargetManagers[index].uniqueId === id) {
  27091. return this.morphTargetManagers[index];
  27092. }
  27093. }
  27094. return null;
  27095. };
  27096. /**
  27097. * Gets a boolean indicating if the given mesh is active
  27098. * @param mesh defines the mesh to look for
  27099. * @returns true if the mesh is in the active list
  27100. */
  27101. Scene.prototype.isActiveMesh = function (mesh) {
  27102. return (this._activeMeshes.indexOf(mesh) !== -1);
  27103. };
  27104. /**
  27105. * Return a the first highlight layer of the scene with a given name.
  27106. * @param name The name of the highlight layer to look for.
  27107. * @return The highlight layer if found otherwise null.
  27108. */
  27109. Scene.prototype.getHighlightLayerByName = function (name) {
  27110. for (var index = 0; index < this.effectLayers.length; index++) {
  27111. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27112. return this.effectLayers[index];
  27113. }
  27114. }
  27115. return null;
  27116. };
  27117. /**
  27118. * Return a the first highlight layer of the scene with a given name.
  27119. * @param name The name of the highlight layer to look for.
  27120. * @return The highlight layer if found otherwise null.
  27121. */
  27122. Scene.prototype.getGlowLayerByName = function (name) {
  27123. for (var index = 0; index < this.effectLayers.length; index++) {
  27124. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27125. return this.effectLayers[index];
  27126. }
  27127. }
  27128. return null;
  27129. };
  27130. Object.defineProperty(Scene.prototype, "uid", {
  27131. /**
  27132. * Return a unique id as a string which can serve as an identifier for the scene
  27133. */
  27134. get: function () {
  27135. if (!this._uid) {
  27136. this._uid = BABYLON.Tools.RandomId();
  27137. }
  27138. return this._uid;
  27139. },
  27140. enumerable: true,
  27141. configurable: true
  27142. });
  27143. /**
  27144. * Add an externaly attached data from its key.
  27145. * This method call will fail and return false, if such key already exists.
  27146. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27147. * @param key the unique key that identifies the data
  27148. * @param data the data object to associate to the key for this Engine instance
  27149. * @return true if no such key were already present and the data was added successfully, false otherwise
  27150. */
  27151. Scene.prototype.addExternalData = function (key, data) {
  27152. if (!this._externalData) {
  27153. this._externalData = new BABYLON.StringDictionary();
  27154. }
  27155. return this._externalData.add(key, data);
  27156. };
  27157. /**
  27158. * Get an externaly attached data from its key
  27159. * @param key the unique key that identifies the data
  27160. * @return the associated data, if present (can be null), or undefined if not present
  27161. */
  27162. Scene.prototype.getExternalData = function (key) {
  27163. if (!this._externalData) {
  27164. return null;
  27165. }
  27166. return this._externalData.get(key);
  27167. };
  27168. /**
  27169. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27170. * @param key the unique key that identifies the data
  27171. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27172. * @return the associated data, can be null if the factory returned null.
  27173. */
  27174. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27175. if (!this._externalData) {
  27176. this._externalData = new BABYLON.StringDictionary();
  27177. }
  27178. return this._externalData.getOrAddWithFactory(key, factory);
  27179. };
  27180. /**
  27181. * Remove an externaly attached data from the Engine instance
  27182. * @param key the unique key that identifies the data
  27183. * @return true if the data was successfully removed, false if it doesn't exist
  27184. */
  27185. Scene.prototype.removeExternalData = function (key) {
  27186. return this._externalData.remove(key);
  27187. };
  27188. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27189. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27190. if (mesh.showSubMeshesBoundingBox) {
  27191. var boundingInfo = subMesh.getBoundingInfo();
  27192. if (boundingInfo !== null && boundingInfo !== undefined) {
  27193. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27194. }
  27195. }
  27196. var material = subMesh.getMaterial();
  27197. if (material !== null && material !== undefined) {
  27198. // Render targets
  27199. if (material.getRenderTargetTextures !== undefined) {
  27200. if (this._processedMaterials.indexOf(material) === -1) {
  27201. this._processedMaterials.push(material);
  27202. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27203. }
  27204. }
  27205. // Dispatch
  27206. this._activeIndices.addCount(subMesh.indexCount, false);
  27207. this._renderingManager.dispatch(subMesh, mesh, material);
  27208. }
  27209. }
  27210. };
  27211. /**
  27212. * Clear the processed materials smart array preventing retention point in material dispose.
  27213. */
  27214. Scene.prototype.freeProcessedMaterials = function () {
  27215. this._processedMaterials.dispose();
  27216. };
  27217. /**
  27218. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27219. */
  27220. Scene.prototype.freeActiveMeshes = function () {
  27221. this._activeMeshes.dispose();
  27222. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27223. this.activeCamera._activeMeshes.dispose();
  27224. }
  27225. if (this.activeCameras) {
  27226. for (var i = 0; i < this.activeCameras.length; i++) {
  27227. var activeCamera = this.activeCameras[i];
  27228. if (activeCamera && activeCamera._activeMeshes) {
  27229. activeCamera._activeMeshes.dispose();
  27230. }
  27231. }
  27232. }
  27233. };
  27234. /**
  27235. * Clear the info related to rendering groups preventing retention points during dispose.
  27236. */
  27237. Scene.prototype.freeRenderingGroups = function () {
  27238. if (this._renderingManager) {
  27239. this._renderingManager.freeRenderingGroups();
  27240. }
  27241. if (this.textures) {
  27242. for (var i = 0; i < this.textures.length; i++) {
  27243. var texture = this.textures[i];
  27244. if (texture && texture.renderList) {
  27245. texture.freeRenderingGroups();
  27246. }
  27247. }
  27248. }
  27249. };
  27250. /** @hidden */
  27251. Scene.prototype._isInIntermediateRendering = function () {
  27252. return this._intermediateRendering;
  27253. };
  27254. /**
  27255. * Defines the current active mesh candidate provider
  27256. * @param provider defines the provider to use
  27257. */
  27258. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27259. this._activeMeshCandidateProvider = provider;
  27260. };
  27261. /**
  27262. * Gets the current active mesh candidate provider
  27263. * @returns the current active mesh candidate provider
  27264. */
  27265. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27266. return this._activeMeshCandidateProvider;
  27267. };
  27268. /**
  27269. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27270. * @returns the current scene
  27271. */
  27272. Scene.prototype.freezeActiveMeshes = function () {
  27273. if (!this.activeCamera) {
  27274. return this;
  27275. }
  27276. if (!this._frustumPlanes) {
  27277. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27278. }
  27279. this._evaluateActiveMeshes();
  27280. this._activeMeshesFrozen = true;
  27281. return this;
  27282. };
  27283. /**
  27284. * Use this function to restart evaluating active meshes on every frame
  27285. * @returns the current scene
  27286. */
  27287. Scene.prototype.unfreezeActiveMeshes = function () {
  27288. this._activeMeshesFrozen = false;
  27289. return this;
  27290. };
  27291. Scene.prototype._evaluateActiveMeshes = function () {
  27292. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27293. return;
  27294. }
  27295. if (!this.activeCamera) {
  27296. return;
  27297. }
  27298. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27299. this.activeCamera._activeMeshes.reset();
  27300. this._activeMeshes.reset();
  27301. this._renderingManager.reset();
  27302. this._processedMaterials.reset();
  27303. this._activeParticleSystems.reset();
  27304. this._activeSkeletons.reset();
  27305. this._softwareSkinnedMeshes.reset();
  27306. if (this._boundingBoxRenderer) {
  27307. this._boundingBoxRenderer.reset();
  27308. }
  27309. // Meshes
  27310. var meshes;
  27311. var len;
  27312. var checkIsEnabled = true;
  27313. // Determine mesh candidates
  27314. if (this._activeMeshCandidateProvider !== undefined) {
  27315. // Use _activeMeshCandidateProvider
  27316. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27317. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27318. if (meshes !== undefined) {
  27319. len = meshes.length;
  27320. }
  27321. else {
  27322. len = 0;
  27323. }
  27324. }
  27325. else if (this._selectionOctree !== undefined) {
  27326. // Octree
  27327. var selection = this._selectionOctree.select(this._frustumPlanes);
  27328. meshes = selection.data;
  27329. len = selection.length;
  27330. }
  27331. else {
  27332. // Full scene traversal
  27333. len = this.meshes.length;
  27334. meshes = this.meshes;
  27335. }
  27336. // Check each mesh
  27337. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27338. mesh = meshes[meshIndex];
  27339. if (mesh.isBlocked) {
  27340. continue;
  27341. }
  27342. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27343. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27344. continue;
  27345. }
  27346. mesh.computeWorldMatrix();
  27347. // Intersections
  27348. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27349. this._meshesForIntersections.pushNoDuplicate(mesh);
  27350. }
  27351. // Switch to current LOD
  27352. meshLOD = mesh.getLOD(this.activeCamera);
  27353. if (meshLOD === undefined || meshLOD === null) {
  27354. continue;
  27355. }
  27356. mesh._preActivate();
  27357. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27358. this._activeMeshes.push(mesh);
  27359. this.activeCamera._activeMeshes.push(mesh);
  27360. mesh._activate(this._renderId);
  27361. if (meshLOD !== mesh) {
  27362. meshLOD._activate(this._renderId);
  27363. }
  27364. this._activeMesh(mesh, meshLOD);
  27365. }
  27366. }
  27367. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27368. // Particle systems
  27369. if (this.particlesEnabled) {
  27370. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27371. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27372. var particleSystem = this.particleSystems[particleIndex];
  27373. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27374. continue;
  27375. }
  27376. var emitter = particleSystem.emitter;
  27377. if (!emitter.position || emitter.isEnabled()) {
  27378. this._activeParticleSystems.push(particleSystem);
  27379. particleSystem.animate();
  27380. this._renderingManager.dispatchParticles(particleSystem);
  27381. }
  27382. }
  27383. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27384. }
  27385. };
  27386. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27387. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27388. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27389. mesh.skeleton.prepare();
  27390. }
  27391. if (!mesh.computeBonesUsingShaders) {
  27392. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27393. }
  27394. }
  27395. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27396. var boundingInfo = sourceMesh.getBoundingInfo();
  27397. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27398. }
  27399. if (mesh !== undefined && mesh !== null
  27400. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27401. // Submeshes Octrees
  27402. var len;
  27403. var subMeshes;
  27404. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27405. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27406. len = intersections.length;
  27407. subMeshes = intersections.data;
  27408. }
  27409. else {
  27410. subMeshes = mesh.subMeshes;
  27411. len = subMeshes.length;
  27412. }
  27413. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27414. subMesh = subMeshes[subIndex];
  27415. this._evaluateSubMesh(subMesh, mesh);
  27416. }
  27417. }
  27418. };
  27419. /**
  27420. * Update the transform matrix to update from the current active camera
  27421. * @param force defines a boolean used to force the update even if cache is up to date
  27422. */
  27423. Scene.prototype.updateTransformMatrix = function (force) {
  27424. if (!this.activeCamera) {
  27425. return;
  27426. }
  27427. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27428. };
  27429. /**
  27430. * 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)
  27431. * @param alternateCamera defines the camera to use
  27432. */
  27433. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27434. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27435. };
  27436. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27437. if (camera && camera._skipRendering) {
  27438. return;
  27439. }
  27440. var engine = this._engine;
  27441. this.activeCamera = camera;
  27442. if (!this.activeCamera)
  27443. throw new Error("Active camera not set");
  27444. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27445. // Viewport
  27446. engine.setViewport(this.activeCamera.viewport);
  27447. // Camera
  27448. this.resetCachedMaterial();
  27449. this._renderId++;
  27450. this.updateTransformMatrix();
  27451. if (camera._alternateCamera) {
  27452. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27453. this._alternateRendering = true;
  27454. }
  27455. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27456. // Meshes
  27457. this._evaluateActiveMeshes();
  27458. // Software skinning
  27459. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27460. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27461. mesh.applySkeleton(mesh.skeleton);
  27462. }
  27463. // Render targets
  27464. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27465. var needsRestoreFrameBuffer = false;
  27466. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27467. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27468. }
  27469. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27470. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27471. }
  27472. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27473. this._intermediateRendering = true;
  27474. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27475. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27476. var renderTarget = this._renderTargets.data[renderIndex];
  27477. if (renderTarget._shouldRender()) {
  27478. this._renderId++;
  27479. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27480. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27481. }
  27482. }
  27483. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27484. this._intermediateRendering = false;
  27485. this._renderId++;
  27486. needsRestoreFrameBuffer = true; // Restore back buffer
  27487. }
  27488. // Render EffecttLayer Texture
  27489. var stencilState = this._engine.getStencilBuffer();
  27490. var renderEffects = false;
  27491. var needStencil = false;
  27492. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27493. this._intermediateRendering = true;
  27494. for (var i = 0; i < this.effectLayers.length; i++) {
  27495. var effectLayer = this.effectLayers[i];
  27496. if (effectLayer.shouldRender() &&
  27497. (!effectLayer.camera ||
  27498. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27499. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27500. renderEffects = true;
  27501. needStencil = needStencil || effectLayer.needStencil();
  27502. var renderTarget = effectLayer._mainTexture;
  27503. if (renderTarget._shouldRender()) {
  27504. this._renderId++;
  27505. renderTarget.render(false, false);
  27506. needsRestoreFrameBuffer = true;
  27507. }
  27508. }
  27509. }
  27510. this._intermediateRendering = false;
  27511. this._renderId++;
  27512. }
  27513. if (needsRestoreFrameBuffer) {
  27514. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27515. }
  27516. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27517. // Prepare Frame
  27518. this.postProcessManager._prepareFrame();
  27519. // Backgrounds
  27520. var layerIndex;
  27521. var layer;
  27522. if (this.layers.length) {
  27523. engine.setDepthBuffer(false);
  27524. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27525. layer = this.layers[layerIndex];
  27526. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27527. layer.render();
  27528. }
  27529. }
  27530. engine.setDepthBuffer(true);
  27531. }
  27532. // Activate effect Layer stencil
  27533. if (needStencil) {
  27534. this._engine.setStencilBuffer(true);
  27535. }
  27536. // Render
  27537. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27538. this._renderingManager.render(null, null, true, true);
  27539. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27540. // Restore effect Layer stencil
  27541. if (needStencil) {
  27542. this._engine.setStencilBuffer(stencilState);
  27543. }
  27544. // Bounding boxes
  27545. if (this._boundingBoxRenderer) {
  27546. this._boundingBoxRenderer.render();
  27547. }
  27548. // Lens flares
  27549. if (this.lensFlaresEnabled) {
  27550. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27551. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27552. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27553. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27554. lensFlareSystem.render();
  27555. }
  27556. }
  27557. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27558. }
  27559. // Effect Layer
  27560. if (renderEffects) {
  27561. engine.setDepthBuffer(false);
  27562. for (var i = 0; i < this.effectLayers.length; i++) {
  27563. if (this.effectLayers[i].shouldRender()) {
  27564. this.effectLayers[i].render();
  27565. }
  27566. }
  27567. engine.setDepthBuffer(true);
  27568. }
  27569. // Foregrounds
  27570. if (this.layers.length) {
  27571. engine.setDepthBuffer(false);
  27572. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27573. layer = this.layers[layerIndex];
  27574. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27575. layer.render();
  27576. }
  27577. }
  27578. engine.setDepthBuffer(true);
  27579. }
  27580. // Finalize frame
  27581. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27582. // Reset some special arrays
  27583. this._renderTargets.reset();
  27584. this._alternateRendering = false;
  27585. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27586. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27587. };
  27588. Scene.prototype._processSubCameras = function (camera) {
  27589. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27590. this._renderForCamera(camera);
  27591. return;
  27592. }
  27593. // rig cameras
  27594. for (var index = 0; index < camera._rigCameras.length; index++) {
  27595. this._renderForCamera(camera._rigCameras[index], camera);
  27596. }
  27597. this.activeCamera = camera;
  27598. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27599. };
  27600. Scene.prototype._checkIntersections = function () {
  27601. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27602. var sourceMesh = this._meshesForIntersections.data[index];
  27603. if (!sourceMesh.actionManager) {
  27604. continue;
  27605. }
  27606. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27607. var action = sourceMesh.actionManager.actions[actionIndex];
  27608. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27609. var parameters = action.getTriggerParameter();
  27610. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27611. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27612. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27613. if (areIntersecting && currentIntersectionInProgress === -1) {
  27614. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27615. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27616. sourceMesh._intersectionsInProgress.push(otherMesh);
  27617. }
  27618. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27619. sourceMesh._intersectionsInProgress.push(otherMesh);
  27620. }
  27621. }
  27622. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27623. //They intersected, and now they don't.
  27624. //is this trigger an exit trigger? execute an event.
  27625. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27626. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27627. }
  27628. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27629. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27630. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27631. return otherMesh === parameterMesh;
  27632. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27633. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27634. }
  27635. }
  27636. }
  27637. }
  27638. }
  27639. };
  27640. /**
  27641. * Render the scene
  27642. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27643. */
  27644. Scene.prototype.render = function (updateCameras) {
  27645. if (updateCameras === void 0) { updateCameras = true; }
  27646. if (this.isDisposed) {
  27647. return;
  27648. }
  27649. this._activeParticles.fetchNewFrame();
  27650. this._totalVertices.fetchNewFrame();
  27651. this._activeIndices.fetchNewFrame();
  27652. this._activeBones.fetchNewFrame();
  27653. this._meshesForIntersections.reset();
  27654. this.resetCachedMaterial();
  27655. this.onBeforeAnimationsObservable.notifyObservers(this);
  27656. // Actions
  27657. if (this.actionManager) {
  27658. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27659. }
  27660. //Simplification Queue
  27661. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27662. this.simplificationQueue.executeNext();
  27663. }
  27664. if (this._engine.isDeterministicLockStep()) {
  27665. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27666. var defaultFPS = (60.0 / 1000.0);
  27667. var defaultFrameTime = 1000 / 60; // frame time in MS
  27668. if (this._physicsEngine) {
  27669. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27670. }
  27671. var stepsTaken = 0;
  27672. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27673. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27674. internalSteps = Math.min(internalSteps, maxSubSteps);
  27675. do {
  27676. this.onBeforeStepObservable.notifyObservers(this);
  27677. // Animations
  27678. this._animationRatio = defaultFrameTime * defaultFPS;
  27679. this._animate();
  27680. this.onAfterAnimationsObservable.notifyObservers(this);
  27681. // Physics
  27682. if (this._physicsEngine) {
  27683. this.onBeforePhysicsObservable.notifyObservers(this);
  27684. this._physicsEngine._step(defaultFrameTime / 1000);
  27685. this.onAfterPhysicsObservable.notifyObservers(this);
  27686. }
  27687. this.onAfterStepObservable.notifyObservers(this);
  27688. this._currentStepId++;
  27689. stepsTaken++;
  27690. deltaTime -= defaultFrameTime;
  27691. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27692. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27693. }
  27694. else {
  27695. // Animations
  27696. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27697. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27698. this._animate();
  27699. this.onAfterAnimationsObservable.notifyObservers(this);
  27700. // Physics
  27701. if (this._physicsEngine) {
  27702. this.onBeforePhysicsObservable.notifyObservers(this);
  27703. this._physicsEngine._step(deltaTime / 1000.0);
  27704. this.onAfterPhysicsObservable.notifyObservers(this);
  27705. }
  27706. }
  27707. // update gamepad manager
  27708. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27709. this._gamepadManager._checkGamepadsStatus();
  27710. }
  27711. // Update Cameras
  27712. if (updateCameras) {
  27713. if (this.activeCameras.length > 0) {
  27714. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27715. var camera = this.activeCameras[cameraIndex];
  27716. camera.update();
  27717. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27718. // rig cameras
  27719. for (var index = 0; index < camera._rigCameras.length; index++) {
  27720. camera._rigCameras[index].update();
  27721. }
  27722. }
  27723. }
  27724. }
  27725. else if (this.activeCamera) {
  27726. this.activeCamera.update();
  27727. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27728. // rig cameras
  27729. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27730. this.activeCamera._rigCameras[index].update();
  27731. }
  27732. }
  27733. }
  27734. }
  27735. // Before render
  27736. this.onBeforeRenderObservable.notifyObservers(this);
  27737. // Customs render targets
  27738. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27739. var engine = this.getEngine();
  27740. var currentActiveCamera = this.activeCamera;
  27741. if (this.renderTargetsEnabled) {
  27742. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27743. this._intermediateRendering = true;
  27744. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27745. var renderTarget = this.customRenderTargets[customIndex];
  27746. if (renderTarget._shouldRender()) {
  27747. this._renderId++;
  27748. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27749. if (!this.activeCamera)
  27750. throw new Error("Active camera not set");
  27751. // Viewport
  27752. engine.setViewport(this.activeCamera.viewport);
  27753. // Camera
  27754. this.updateTransformMatrix();
  27755. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27756. }
  27757. }
  27758. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27759. this._intermediateRendering = false;
  27760. this._renderId++;
  27761. }
  27762. // Restore back buffer
  27763. if (this.customRenderTargets.length > 0) {
  27764. engine.restoreDefaultFramebuffer();
  27765. }
  27766. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27767. this.activeCamera = currentActiveCamera;
  27768. // Procedural textures
  27769. if (this.proceduralTexturesEnabled) {
  27770. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27771. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27772. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27773. if (proceduralTexture._shouldRender()) {
  27774. proceduralTexture.render();
  27775. }
  27776. }
  27777. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27778. }
  27779. // Clear
  27780. if (this.autoClearDepthAndStencil || this.autoClear) {
  27781. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27782. }
  27783. // Shadows
  27784. if (this.shadowsEnabled) {
  27785. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27786. var light = this.lights[lightIndex];
  27787. var shadowGenerator = light.getShadowGenerator();
  27788. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27789. var shadowMap = (shadowGenerator.getShadowMap());
  27790. if (this.textures.indexOf(shadowMap) !== -1) {
  27791. this._renderTargets.push(shadowMap);
  27792. }
  27793. }
  27794. }
  27795. }
  27796. // Depth renderer
  27797. for (var key in this._depthRenderer) {
  27798. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27799. }
  27800. // Geometry renderer
  27801. if (this._geometryBufferRenderer) {
  27802. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27803. }
  27804. // RenderPipeline
  27805. if (this._postProcessRenderPipelineManager) {
  27806. this._postProcessRenderPipelineManager.update();
  27807. }
  27808. // Multi-cameras?
  27809. if (this.activeCameras.length > 0) {
  27810. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27811. if (cameraIndex > 0) {
  27812. this._engine.clear(null, false, true, true);
  27813. }
  27814. this._processSubCameras(this.activeCameras[cameraIndex]);
  27815. }
  27816. }
  27817. else {
  27818. if (!this.activeCamera) {
  27819. throw new Error("No camera defined");
  27820. }
  27821. this._processSubCameras(this.activeCamera);
  27822. }
  27823. // Intersection checks
  27824. this._checkIntersections();
  27825. // Update the audio listener attached to the camera
  27826. if (BABYLON.AudioEngine) {
  27827. this._updateAudioParameters();
  27828. }
  27829. // After render
  27830. if (this.afterRender) {
  27831. this.afterRender();
  27832. }
  27833. this.onAfterRenderObservable.notifyObservers(this);
  27834. // Cleaning
  27835. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27836. var data = this._toBeDisposed.data[index];
  27837. if (data) {
  27838. data.dispose();
  27839. }
  27840. this._toBeDisposed[index] = null;
  27841. }
  27842. this._toBeDisposed.reset();
  27843. if (this.dumpNextRenderTargets) {
  27844. this.dumpNextRenderTargets = false;
  27845. }
  27846. this._activeBones.addCount(0, true);
  27847. this._activeIndices.addCount(0, true);
  27848. this._activeParticles.addCount(0, true);
  27849. };
  27850. Scene.prototype._updateAudioParameters = function () {
  27851. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27852. return;
  27853. }
  27854. var listeningCamera;
  27855. var audioEngine = BABYLON.Engine.audioEngine;
  27856. if (this.activeCameras.length > 0) {
  27857. listeningCamera = this.activeCameras[0];
  27858. }
  27859. else {
  27860. listeningCamera = this.activeCamera;
  27861. }
  27862. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27863. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27864. // for VR cameras
  27865. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27866. listeningCamera = listeningCamera.rigCameras[0];
  27867. }
  27868. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27869. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27870. cameraDirection.normalize();
  27871. // To avoid some errors on GearVR
  27872. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27873. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27874. }
  27875. var i;
  27876. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27877. var sound = this.mainSoundTrack.soundCollection[i];
  27878. if (sound.useCustomAttenuation) {
  27879. sound.updateDistanceFromListener();
  27880. }
  27881. }
  27882. for (i = 0; i < this.soundTracks.length; i++) {
  27883. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27884. sound = this.soundTracks[i].soundCollection[j];
  27885. if (sound.useCustomAttenuation) {
  27886. sound.updateDistanceFromListener();
  27887. }
  27888. }
  27889. }
  27890. }
  27891. };
  27892. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27893. // Audio
  27894. /**
  27895. * Gets or sets if audio support is enabled
  27896. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27897. */
  27898. get: function () {
  27899. return this._audioEnabled;
  27900. },
  27901. set: function (value) {
  27902. this._audioEnabled = value;
  27903. if (BABYLON.AudioEngine) {
  27904. if (this._audioEnabled) {
  27905. this._enableAudio();
  27906. }
  27907. else {
  27908. this._disableAudio();
  27909. }
  27910. }
  27911. },
  27912. enumerable: true,
  27913. configurable: true
  27914. });
  27915. Scene.prototype._disableAudio = function () {
  27916. var i;
  27917. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27918. this.mainSoundTrack.soundCollection[i].pause();
  27919. }
  27920. for (i = 0; i < this.soundTracks.length; i++) {
  27921. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27922. this.soundTracks[i].soundCollection[j].pause();
  27923. }
  27924. }
  27925. };
  27926. Scene.prototype._enableAudio = function () {
  27927. var i;
  27928. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27929. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27930. this.mainSoundTrack.soundCollection[i].play();
  27931. }
  27932. }
  27933. for (i = 0; i < this.soundTracks.length; i++) {
  27934. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27935. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27936. this.soundTracks[i].soundCollection[j].play();
  27937. }
  27938. }
  27939. }
  27940. };
  27941. Object.defineProperty(Scene.prototype, "headphone", {
  27942. /**
  27943. * Gets or sets if audio will be output to headphones
  27944. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27945. */
  27946. get: function () {
  27947. return this._headphone;
  27948. },
  27949. set: function (value) {
  27950. this._headphone = value;
  27951. if (BABYLON.AudioEngine) {
  27952. if (this._headphone) {
  27953. this._switchAudioModeForHeadphones();
  27954. }
  27955. else {
  27956. this._switchAudioModeForNormalSpeakers();
  27957. }
  27958. }
  27959. },
  27960. enumerable: true,
  27961. configurable: true
  27962. });
  27963. Scene.prototype._switchAudioModeForHeadphones = function () {
  27964. this.mainSoundTrack.switchPanningModelToHRTF();
  27965. for (var i = 0; i < this.soundTracks.length; i++) {
  27966. this.soundTracks[i].switchPanningModelToHRTF();
  27967. }
  27968. };
  27969. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27970. this.mainSoundTrack.switchPanningModelToEqualPower();
  27971. for (var i = 0; i < this.soundTracks.length; i++) {
  27972. this.soundTracks[i].switchPanningModelToEqualPower();
  27973. }
  27974. };
  27975. /**
  27976. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27977. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27978. * @returns the created depth renderer
  27979. */
  27980. Scene.prototype.enableDepthRenderer = function (camera) {
  27981. camera = camera || this.activeCamera;
  27982. if (!camera) {
  27983. throw "No camera available to enable depth renderer";
  27984. }
  27985. if (!this._depthRenderer[camera.id]) {
  27986. var textureType = 0;
  27987. if (this._engine.getCaps().textureHalfFloatRender) {
  27988. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27989. }
  27990. else if (this._engine.getCaps().textureFloatRender) {
  27991. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27992. }
  27993. else {
  27994. throw "Depth renderer does not support int texture type";
  27995. }
  27996. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27997. }
  27998. return this._depthRenderer[camera.id];
  27999. };
  28000. /**
  28001. * Disables a depth renderer for a given camera
  28002. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28003. */
  28004. Scene.prototype.disableDepthRenderer = function (camera) {
  28005. camera = camera || this.activeCamera;
  28006. if (!camera || !this._depthRenderer[camera.id]) {
  28007. return;
  28008. }
  28009. this._depthRenderer[camera.id].dispose();
  28010. delete this._depthRenderer[camera.id];
  28011. };
  28012. /**
  28013. * Enables a GeometryBufferRender and associates it with the scene
  28014. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28015. * @returns the GeometryBufferRenderer
  28016. */
  28017. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28018. if (ratio === void 0) { ratio = 1; }
  28019. if (this._geometryBufferRenderer) {
  28020. return this._geometryBufferRenderer;
  28021. }
  28022. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28023. if (!this._geometryBufferRenderer.isSupported) {
  28024. this._geometryBufferRenderer = null;
  28025. }
  28026. return this._geometryBufferRenderer;
  28027. };
  28028. /**
  28029. * Disables the GeometryBufferRender associated with the scene
  28030. */
  28031. Scene.prototype.disableGeometryBufferRenderer = function () {
  28032. if (!this._geometryBufferRenderer) {
  28033. return;
  28034. }
  28035. this._geometryBufferRenderer.dispose();
  28036. this._geometryBufferRenderer = null;
  28037. };
  28038. /**
  28039. * Freeze all materials
  28040. * A frozen material will not be updatable but should be faster to render
  28041. */
  28042. Scene.prototype.freezeMaterials = function () {
  28043. for (var i = 0; i < this.materials.length; i++) {
  28044. this.materials[i].freeze();
  28045. }
  28046. };
  28047. /**
  28048. * Unfreeze all materials
  28049. * A frozen material will not be updatable but should be faster to render
  28050. */
  28051. Scene.prototype.unfreezeMaterials = function () {
  28052. for (var i = 0; i < this.materials.length; i++) {
  28053. this.materials[i].unfreeze();
  28054. }
  28055. };
  28056. /**
  28057. * Releases all held ressources
  28058. */
  28059. Scene.prototype.dispose = function () {
  28060. this.beforeRender = null;
  28061. this.afterRender = null;
  28062. this.skeletons = [];
  28063. this.morphTargetManagers = [];
  28064. this.importedMeshesFiles = new Array();
  28065. this.stopAllAnimations();
  28066. this.resetCachedMaterial();
  28067. for (var key in this._depthRenderer) {
  28068. this._depthRenderer[key].dispose();
  28069. }
  28070. if (this._gamepadManager) {
  28071. this._gamepadManager.dispose();
  28072. this._gamepadManager = null;
  28073. }
  28074. // Smart arrays
  28075. if (this.activeCamera) {
  28076. this.activeCamera._activeMeshes.dispose();
  28077. this.activeCamera = null;
  28078. }
  28079. this._activeMeshes.dispose();
  28080. this._renderingManager.dispose();
  28081. this._processedMaterials.dispose();
  28082. this._activeParticleSystems.dispose();
  28083. this._activeSkeletons.dispose();
  28084. this._softwareSkinnedMeshes.dispose();
  28085. this._renderTargets.dispose();
  28086. this._registeredForLateAnimationBindings.dispose();
  28087. if (this._boundingBoxRenderer) {
  28088. this._boundingBoxRenderer.dispose();
  28089. }
  28090. this._meshesForIntersections.dispose();
  28091. this._toBeDisposed.dispose();
  28092. // Abort active requests
  28093. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28094. var request = _a[_i];
  28095. request.abort();
  28096. }
  28097. // Debug layer
  28098. if (this._debugLayer) {
  28099. this._debugLayer.hide();
  28100. }
  28101. // Events
  28102. this.onDisposeObservable.notifyObservers(this);
  28103. this.onDisposeObservable.clear();
  28104. this.onBeforeRenderObservable.clear();
  28105. this.onAfterRenderObservable.clear();
  28106. this.onBeforeRenderTargetsRenderObservable.clear();
  28107. this.onAfterRenderTargetsRenderObservable.clear();
  28108. this.onAfterStepObservable.clear();
  28109. this.onBeforeStepObservable.clear();
  28110. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28111. this.onAfterActiveMeshesEvaluationObservable.clear();
  28112. this.onBeforeParticlesRenderingObservable.clear();
  28113. this.onAfterParticlesRenderingObservable.clear();
  28114. this.onBeforeSpritesRenderingObservable.clear();
  28115. this.onAfterSpritesRenderingObservable.clear();
  28116. this.onBeforeDrawPhaseObservable.clear();
  28117. this.onAfterDrawPhaseObservable.clear();
  28118. this.onBeforePhysicsObservable.clear();
  28119. this.onAfterPhysicsObservable.clear();
  28120. this.onBeforeAnimationsObservable.clear();
  28121. this.onAfterAnimationsObservable.clear();
  28122. this.onDataLoadedObservable.clear();
  28123. this.detachControl();
  28124. // Release sounds & sounds tracks
  28125. if (BABYLON.AudioEngine) {
  28126. this.disposeSounds();
  28127. }
  28128. // VR Helper
  28129. if (this.VRHelper) {
  28130. this.VRHelper.dispose();
  28131. }
  28132. // Detach cameras
  28133. var canvas = this._engine.getRenderingCanvas();
  28134. if (canvas) {
  28135. var index;
  28136. for (index = 0; index < this.cameras.length; index++) {
  28137. this.cameras[index].detachControl(canvas);
  28138. }
  28139. }
  28140. // Release animation groups
  28141. while (this.animationGroups.length) {
  28142. this.animationGroups[0].dispose();
  28143. }
  28144. // Release lights
  28145. while (this.lights.length) {
  28146. this.lights[0].dispose();
  28147. }
  28148. // Release meshes
  28149. while (this.meshes.length) {
  28150. this.meshes[0].dispose(true);
  28151. }
  28152. while (this.transformNodes.length) {
  28153. this.removeTransformNode(this.transformNodes[0]);
  28154. }
  28155. // Release cameras
  28156. while (this.cameras.length) {
  28157. this.cameras[0].dispose();
  28158. }
  28159. // Release materials
  28160. if (this.defaultMaterial) {
  28161. this.defaultMaterial.dispose();
  28162. }
  28163. while (this.multiMaterials.length) {
  28164. this.multiMaterials[0].dispose();
  28165. }
  28166. while (this.materials.length) {
  28167. this.materials[0].dispose();
  28168. }
  28169. // Release particles
  28170. while (this.particleSystems.length) {
  28171. this.particleSystems[0].dispose();
  28172. }
  28173. // Release sprites
  28174. while (this.spriteManagers.length) {
  28175. this.spriteManagers[0].dispose();
  28176. }
  28177. // Release postProcesses
  28178. while (this.postProcesses.length) {
  28179. this.postProcesses[0].dispose();
  28180. }
  28181. // Release layers
  28182. while (this.layers.length) {
  28183. this.layers[0].dispose();
  28184. }
  28185. while (this.effectLayers.length) {
  28186. this.effectLayers[0].dispose();
  28187. }
  28188. // Release textures
  28189. while (this.textures.length) {
  28190. this.textures[0].dispose();
  28191. }
  28192. // Release UBO
  28193. this._sceneUbo.dispose();
  28194. if (this._alternateSceneUbo) {
  28195. this._alternateSceneUbo.dispose();
  28196. }
  28197. // Post-processes
  28198. this.postProcessManager.dispose();
  28199. if (this._postProcessRenderPipelineManager) {
  28200. this._postProcessRenderPipelineManager.dispose();
  28201. }
  28202. // Physics
  28203. if (this._physicsEngine) {
  28204. this.disablePhysicsEngine();
  28205. }
  28206. // Remove from engine
  28207. index = this._engine.scenes.indexOf(this);
  28208. if (index > -1) {
  28209. this._engine.scenes.splice(index, 1);
  28210. }
  28211. this._engine.wipeCaches(true);
  28212. this._isDisposed = true;
  28213. };
  28214. Object.defineProperty(Scene.prototype, "isDisposed", {
  28215. /**
  28216. * Gets if the scene is already disposed
  28217. */
  28218. get: function () {
  28219. return this._isDisposed;
  28220. },
  28221. enumerable: true,
  28222. configurable: true
  28223. });
  28224. /**
  28225. * Releases sounds & soundtracks
  28226. */
  28227. Scene.prototype.disposeSounds = function () {
  28228. if (!this._mainSoundTrack) {
  28229. return;
  28230. }
  28231. this.mainSoundTrack.dispose();
  28232. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28233. this.soundTracks[scIndex].dispose();
  28234. }
  28235. };
  28236. /**
  28237. * Call this function to reduce memory footprint of the scene.
  28238. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28239. */
  28240. Scene.prototype.clearCachedVertexData = function () {
  28241. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28242. var mesh = this.meshes[meshIndex];
  28243. var geometry = mesh.geometry;
  28244. if (geometry) {
  28245. geometry._indices = [];
  28246. for (var vbName in geometry._vertexBuffers) {
  28247. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28248. continue;
  28249. }
  28250. geometry._vertexBuffers[vbName]._buffer._data = null;
  28251. }
  28252. }
  28253. }
  28254. };
  28255. /**
  28256. * This function will remove the local cached buffer data from texture.
  28257. * It will save memory but will prevent the texture from being rebuilt
  28258. */
  28259. Scene.prototype.cleanCachedTextureBuffer = function () {
  28260. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28261. var baseTexture = _a[_i];
  28262. var buffer = baseTexture._buffer;
  28263. if (buffer) {
  28264. baseTexture._buffer = null;
  28265. }
  28266. }
  28267. };
  28268. // Octrees
  28269. /**
  28270. * Get the world extend vectors with an optional filter
  28271. *
  28272. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28273. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28274. */
  28275. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28276. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28277. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28278. filterPredicate = filterPredicate || (function () { return true; });
  28279. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28280. mesh.computeWorldMatrix(true);
  28281. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28282. return;
  28283. }
  28284. var boundingInfo = mesh.getBoundingInfo();
  28285. var minBox = boundingInfo.boundingBox.minimumWorld;
  28286. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28287. BABYLON.Tools.CheckExtends(minBox, min, max);
  28288. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28289. });
  28290. return {
  28291. min: min,
  28292. max: max
  28293. };
  28294. };
  28295. /**
  28296. * Creates or updates the octree used to boost selection (picking)
  28297. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28298. * @param maxCapacity defines the maximum capacity per leaf
  28299. * @param maxDepth defines the maximum depth of the octree
  28300. * @returns an octree of AbstractMesh
  28301. */
  28302. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28303. if (maxCapacity === void 0) { maxCapacity = 64; }
  28304. if (maxDepth === void 0) { maxDepth = 2; }
  28305. if (!this._selectionOctree) {
  28306. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28307. }
  28308. var worldExtends = this.getWorldExtends();
  28309. // Update octree
  28310. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28311. return this._selectionOctree;
  28312. };
  28313. // Picking
  28314. /**
  28315. * Creates a ray that can be used to pick in the scene
  28316. * @param x defines the x coordinate of the origin (on-screen)
  28317. * @param y defines the y coordinate of the origin (on-screen)
  28318. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28319. * @param camera defines the camera to use for the picking
  28320. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28321. * @returns a Ray
  28322. */
  28323. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28324. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28325. var result = BABYLON.Ray.Zero();
  28326. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28327. return result;
  28328. };
  28329. /**
  28330. * Creates a ray that can be used to pick in the scene
  28331. * @param x defines the x coordinate of the origin (on-screen)
  28332. * @param y defines the y coordinate of the origin (on-screen)
  28333. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28334. * @param result defines the ray where to store the picking ray
  28335. * @param camera defines the camera to use for the picking
  28336. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28337. * @returns the current scene
  28338. */
  28339. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28340. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28341. var engine = this._engine;
  28342. if (!camera) {
  28343. if (!this.activeCamera)
  28344. throw new Error("Active camera not set");
  28345. camera = this.activeCamera;
  28346. }
  28347. var cameraViewport = camera.viewport;
  28348. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28349. // Moving coordinates to local viewport world
  28350. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28351. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28352. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28353. return this;
  28354. };
  28355. /**
  28356. * Creates a ray that can be used to pick in the scene
  28357. * @param x defines the x coordinate of the origin (on-screen)
  28358. * @param y defines the y coordinate of the origin (on-screen)
  28359. * @param camera defines the camera to use for the picking
  28360. * @returns a Ray
  28361. */
  28362. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28363. var result = BABYLON.Ray.Zero();
  28364. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28365. return result;
  28366. };
  28367. /**
  28368. * Creates a ray that can be used to pick in the scene
  28369. * @param x defines the x coordinate of the origin (on-screen)
  28370. * @param y defines the y coordinate of the origin (on-screen)
  28371. * @param result defines the ray where to store the picking ray
  28372. * @param camera defines the camera to use for the picking
  28373. * @returns the current scene
  28374. */
  28375. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28376. if (!BABYLON.PickingInfo) {
  28377. return this;
  28378. }
  28379. var engine = this._engine;
  28380. if (!camera) {
  28381. if (!this.activeCamera)
  28382. throw new Error("Active camera not set");
  28383. camera = this.activeCamera;
  28384. }
  28385. var cameraViewport = camera.viewport;
  28386. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28387. var identity = BABYLON.Matrix.Identity();
  28388. // Moving coordinates to local viewport world
  28389. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28390. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28391. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28392. return this;
  28393. };
  28394. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28395. if (!BABYLON.PickingInfo) {
  28396. return null;
  28397. }
  28398. var pickingInfo = null;
  28399. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28400. var mesh = this.meshes[meshIndex];
  28401. if (predicate) {
  28402. if (!predicate(mesh)) {
  28403. continue;
  28404. }
  28405. }
  28406. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28407. continue;
  28408. }
  28409. var world = mesh.getWorldMatrix();
  28410. var ray = rayFunction(world);
  28411. var result = mesh.intersects(ray, fastCheck);
  28412. if (!result || !result.hit)
  28413. continue;
  28414. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28415. continue;
  28416. pickingInfo = result;
  28417. if (fastCheck) {
  28418. break;
  28419. }
  28420. }
  28421. return pickingInfo || new BABYLON.PickingInfo();
  28422. };
  28423. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28424. if (!BABYLON.PickingInfo) {
  28425. return null;
  28426. }
  28427. var pickingInfos = new Array();
  28428. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28429. var mesh = this.meshes[meshIndex];
  28430. if (predicate) {
  28431. if (!predicate(mesh)) {
  28432. continue;
  28433. }
  28434. }
  28435. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28436. continue;
  28437. }
  28438. var world = mesh.getWorldMatrix();
  28439. var ray = rayFunction(world);
  28440. var result = mesh.intersects(ray, false);
  28441. if (!result || !result.hit)
  28442. continue;
  28443. pickingInfos.push(result);
  28444. }
  28445. return pickingInfos;
  28446. };
  28447. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28448. if (!BABYLON.PickingInfo) {
  28449. return null;
  28450. }
  28451. var pickingInfo = null;
  28452. if (!camera) {
  28453. if (!this.activeCamera) {
  28454. return null;
  28455. }
  28456. camera = this.activeCamera;
  28457. }
  28458. if (this.spriteManagers.length > 0) {
  28459. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28460. var spriteManager = this.spriteManagers[spriteIndex];
  28461. if (!spriteManager.isPickable) {
  28462. continue;
  28463. }
  28464. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28465. if (!result || !result.hit)
  28466. continue;
  28467. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28468. continue;
  28469. pickingInfo = result;
  28470. if (fastCheck) {
  28471. break;
  28472. }
  28473. }
  28474. }
  28475. return pickingInfo || new BABYLON.PickingInfo();
  28476. };
  28477. /** Launch a ray to try to pick a mesh in the scene
  28478. * @param x position on screen
  28479. * @param y position on screen
  28480. * @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
  28481. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28482. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28483. * @returns a PickingInfo
  28484. */
  28485. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28486. var _this = this;
  28487. if (!BABYLON.PickingInfo) {
  28488. return null;
  28489. }
  28490. return this._internalPick(function (world) {
  28491. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28492. return _this._tempPickingRay;
  28493. }, predicate, fastCheck);
  28494. };
  28495. /** Launch a ray to try to pick a sprite in the scene
  28496. * @param x position on screen
  28497. * @param y position on screen
  28498. * @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
  28499. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28500. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28501. * @returns a PickingInfo
  28502. */
  28503. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28504. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28505. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28506. };
  28507. /** Use the given ray to pick a mesh in the scene
  28508. * @param ray The ray to use to pick meshes
  28509. * @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
  28510. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28511. * @returns a PickingInfo
  28512. */
  28513. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28514. var _this = this;
  28515. var result = this._internalPick(function (world) {
  28516. if (!_this._pickWithRayInverseMatrix) {
  28517. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28518. }
  28519. world.invertToRef(_this._pickWithRayInverseMatrix);
  28520. if (!_this._cachedRayForTransform) {
  28521. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28522. }
  28523. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28524. return _this._cachedRayForTransform;
  28525. }, predicate, fastCheck);
  28526. if (result) {
  28527. result.ray = ray;
  28528. }
  28529. return result;
  28530. };
  28531. /**
  28532. * Launch a ray to try to pick a mesh in the scene
  28533. * @param x X position on screen
  28534. * @param y Y position on screen
  28535. * @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
  28536. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28537. * @returns an array of PickingInfo
  28538. */
  28539. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28540. var _this = this;
  28541. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28542. };
  28543. /**
  28544. * Launch a ray to try to pick a mesh in the scene
  28545. * @param ray Ray to use
  28546. * @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
  28547. * @returns an array of PickingInfo
  28548. */
  28549. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28550. var _this = this;
  28551. return this._internalMultiPick(function (world) {
  28552. if (!_this._pickWithRayInverseMatrix) {
  28553. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28554. }
  28555. world.invertToRef(_this._pickWithRayInverseMatrix);
  28556. if (!_this._cachedRayForTransform) {
  28557. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28558. }
  28559. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28560. return _this._cachedRayForTransform;
  28561. }, predicate);
  28562. };
  28563. /**
  28564. * Force the value of meshUnderPointer
  28565. * @param mesh defines the mesh to use
  28566. */
  28567. Scene.prototype.setPointerOverMesh = function (mesh) {
  28568. if (this._pointerOverMesh === mesh) {
  28569. return;
  28570. }
  28571. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28572. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28573. }
  28574. this._pointerOverMesh = mesh;
  28575. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28576. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28577. }
  28578. };
  28579. /**
  28580. * Gets the mesh under the pointer
  28581. * @returns a Mesh or null if no mesh is under the pointer
  28582. */
  28583. Scene.prototype.getPointerOverMesh = function () {
  28584. return this._pointerOverMesh;
  28585. };
  28586. /**
  28587. * Force the sprite under the pointer
  28588. * @param sprite defines the sprite to use
  28589. */
  28590. Scene.prototype.setPointerOverSprite = function (sprite) {
  28591. if (this._pointerOverSprite === sprite) {
  28592. return;
  28593. }
  28594. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28595. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28596. }
  28597. this._pointerOverSprite = sprite;
  28598. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28599. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28600. }
  28601. };
  28602. /**
  28603. * Gets the sprite under the pointer
  28604. * @returns a Sprite or null if no sprite is under the pointer
  28605. */
  28606. Scene.prototype.getPointerOverSprite = function () {
  28607. return this._pointerOverSprite;
  28608. };
  28609. // Physics
  28610. /**
  28611. * Gets the current physics engine
  28612. * @returns a PhysicsEngine or null if none attached
  28613. */
  28614. Scene.prototype.getPhysicsEngine = function () {
  28615. return this._physicsEngine;
  28616. };
  28617. /**
  28618. * Enables physics to the current scene
  28619. * @param gravity defines the scene's gravity for the physics engine
  28620. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28621. * @return a boolean indicating if the physics engine was initialized
  28622. */
  28623. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28624. if (gravity === void 0) { gravity = null; }
  28625. if (this._physicsEngine) {
  28626. return true;
  28627. }
  28628. try {
  28629. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28630. return true;
  28631. }
  28632. catch (e) {
  28633. BABYLON.Tools.Error(e.message);
  28634. return false;
  28635. }
  28636. };
  28637. /**
  28638. * Disables and disposes the physics engine associated with the scene
  28639. */
  28640. Scene.prototype.disablePhysicsEngine = function () {
  28641. if (!this._physicsEngine) {
  28642. return;
  28643. }
  28644. this._physicsEngine.dispose();
  28645. this._physicsEngine = null;
  28646. };
  28647. /**
  28648. * Gets a boolean indicating if there is an active physics engine
  28649. * @returns a boolean indicating if there is an active physics engine
  28650. */
  28651. Scene.prototype.isPhysicsEnabled = function () {
  28652. return this._physicsEngine !== undefined;
  28653. };
  28654. /**
  28655. * Deletes a physics compound impostor
  28656. * @param compound defines the compound to delete
  28657. */
  28658. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28659. var mesh = compound.parts[0].mesh;
  28660. if (mesh.physicsImpostor) {
  28661. mesh.physicsImpostor.dispose( /*true*/);
  28662. mesh.physicsImpostor = null;
  28663. }
  28664. };
  28665. // Misc.
  28666. /** @hidden */
  28667. Scene.prototype._rebuildGeometries = function () {
  28668. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28669. var geometry = _a[_i];
  28670. geometry._rebuild();
  28671. }
  28672. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28673. var mesh = _c[_b];
  28674. mesh._rebuild();
  28675. }
  28676. if (this.postProcessManager) {
  28677. this.postProcessManager._rebuild();
  28678. }
  28679. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28680. var layer = _e[_d];
  28681. layer._rebuild();
  28682. }
  28683. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28684. var effectLayer = _g[_f];
  28685. effectLayer._rebuild();
  28686. }
  28687. if (this._boundingBoxRenderer) {
  28688. this._boundingBoxRenderer._rebuild();
  28689. }
  28690. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28691. var system = _j[_h];
  28692. system.rebuild();
  28693. }
  28694. if (this._postProcessRenderPipelineManager) {
  28695. this._postProcessRenderPipelineManager._rebuild();
  28696. }
  28697. };
  28698. /** @hidden */
  28699. Scene.prototype._rebuildTextures = function () {
  28700. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28701. var texture = _a[_i];
  28702. texture._rebuild();
  28703. }
  28704. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28705. };
  28706. /**
  28707. * Creates a default light for the scene.
  28708. * @param replace Whether to replace the existing lights in the scene.
  28709. */
  28710. Scene.prototype.createDefaultLight = function (replace) {
  28711. if (replace === void 0) { replace = false; }
  28712. // Dispose existing light in replace mode.
  28713. if (replace) {
  28714. if (this.lights) {
  28715. for (var i = 0; i < this.lights.length; i++) {
  28716. this.lights[i].dispose();
  28717. }
  28718. }
  28719. }
  28720. // Light
  28721. if (this.lights.length === 0) {
  28722. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28723. }
  28724. };
  28725. /**
  28726. * Creates a default camera for the scene.
  28727. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28728. * @param replace Whether to replace the existing active camera in the scene.
  28729. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28730. */
  28731. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28732. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28733. if (replace === void 0) { replace = false; }
  28734. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28735. // Dispose existing camera in replace mode.
  28736. if (replace) {
  28737. if (this.activeCamera) {
  28738. this.activeCamera.dispose();
  28739. this.activeCamera = null;
  28740. }
  28741. }
  28742. // Camera
  28743. if (!this.activeCamera) {
  28744. var worldExtends = this.getWorldExtends();
  28745. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28746. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28747. var camera;
  28748. var radius = worldSize.length() * 1.5;
  28749. // empty scene scenario!
  28750. if (!isFinite(radius)) {
  28751. radius = 1;
  28752. worldCenter.copyFromFloats(0, 0, 0);
  28753. }
  28754. if (createArcRotateCamera) {
  28755. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28756. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28757. arcRotateCamera.wheelPrecision = 100 / radius;
  28758. camera = arcRotateCamera;
  28759. }
  28760. else {
  28761. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28762. freeCamera.setTarget(worldCenter);
  28763. camera = freeCamera;
  28764. }
  28765. camera.minZ = radius * 0.01;
  28766. camera.maxZ = radius * 1000;
  28767. camera.speed = radius * 0.2;
  28768. this.activeCamera = camera;
  28769. var canvas = this.getEngine().getRenderingCanvas();
  28770. if (attachCameraControls && canvas) {
  28771. camera.attachControl(canvas);
  28772. }
  28773. }
  28774. };
  28775. /**
  28776. * Creates a default camera and a default light
  28777. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28778. * @param replace defines if the camera and/or light will replace the existing ones
  28779. * @param attachCameraControls defines if attachControl will be called on the new camera
  28780. */
  28781. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28782. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28783. if (replace === void 0) { replace = false; }
  28784. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28785. this.createDefaultLight(replace);
  28786. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28787. };
  28788. /**
  28789. * Creates a new sky box
  28790. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28791. * @param environmentTexture defines the texture to use as environment texture
  28792. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28793. * @param scale defines the overall scale of the skybox
  28794. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28795. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28796. * @returns a new mesh holding the sky box
  28797. */
  28798. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28799. if (pbr === void 0) { pbr = false; }
  28800. if (scale === void 0) { scale = 1000; }
  28801. if (blur === void 0) { blur = 0; }
  28802. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28803. if (!environmentTexture) {
  28804. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28805. return null;
  28806. }
  28807. if (setGlobalEnvTexture) {
  28808. if (environmentTexture) {
  28809. this.environmentTexture = environmentTexture;
  28810. }
  28811. }
  28812. // Skybox
  28813. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28814. if (pbr) {
  28815. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28816. hdrSkyboxMaterial.backFaceCulling = false;
  28817. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28818. if (hdrSkyboxMaterial.reflectionTexture) {
  28819. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28820. }
  28821. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28822. hdrSkyboxMaterial.disableLighting = true;
  28823. hdrSkyboxMaterial.twoSidedLighting = true;
  28824. hdrSkybox.infiniteDistance = true;
  28825. hdrSkybox.material = hdrSkyboxMaterial;
  28826. }
  28827. else {
  28828. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28829. skyboxMaterial.backFaceCulling = false;
  28830. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28831. if (skyboxMaterial.reflectionTexture) {
  28832. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28833. }
  28834. skyboxMaterial.disableLighting = true;
  28835. hdrSkybox.infiniteDistance = true;
  28836. hdrSkybox.material = skyboxMaterial;
  28837. }
  28838. return hdrSkybox;
  28839. };
  28840. /**
  28841. * Creates a new environment
  28842. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28843. * @param options defines the options you can use to configure the environment
  28844. * @returns the new EnvironmentHelper
  28845. */
  28846. Scene.prototype.createDefaultEnvironment = function (options) {
  28847. if (BABYLON.EnvironmentHelper) {
  28848. return new BABYLON.EnvironmentHelper(options, this);
  28849. }
  28850. return null;
  28851. };
  28852. /**
  28853. * Creates a new VREXperienceHelper
  28854. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28855. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28856. * @returns a new VREXperienceHelper
  28857. */
  28858. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28859. if (webVROptions === void 0) { webVROptions = {}; }
  28860. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28861. };
  28862. // Tags
  28863. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28864. if (tagsQuery === undefined) {
  28865. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28866. return list;
  28867. }
  28868. var listByTags = [];
  28869. forEach = forEach || (function (item) { return; });
  28870. for (var i in list) {
  28871. var item = list[i];
  28872. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28873. listByTags.push(item);
  28874. forEach(item);
  28875. }
  28876. }
  28877. return listByTags;
  28878. };
  28879. /**
  28880. * Get a list of meshes by tags
  28881. * @param tagsQuery defines the tags query to use
  28882. * @param forEach defines a predicate used to filter results
  28883. * @returns an array of Mesh
  28884. */
  28885. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28886. return this._getByTags(this.meshes, tagsQuery, forEach);
  28887. };
  28888. /**
  28889. * Get a list of cameras by tags
  28890. * @param tagsQuery defines the tags query to use
  28891. * @param forEach defines a predicate used to filter results
  28892. * @returns an array of Camera
  28893. */
  28894. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28895. return this._getByTags(this.cameras, tagsQuery, forEach);
  28896. };
  28897. /**
  28898. * Get a list of lights by tags
  28899. * @param tagsQuery defines the tags query to use
  28900. * @param forEach defines a predicate used to filter results
  28901. * @returns an array of Light
  28902. */
  28903. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28904. return this._getByTags(this.lights, tagsQuery, forEach);
  28905. };
  28906. /**
  28907. * Get a list of materials by tags
  28908. * @param tagsQuery defines the tags query to use
  28909. * @param forEach defines a predicate used to filter results
  28910. * @returns an array of Material
  28911. */
  28912. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28913. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28914. };
  28915. /**
  28916. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28917. * This allowed control for front to back rendering or reversly depending of the special needs.
  28918. *
  28919. * @param renderingGroupId The rendering group id corresponding to its index
  28920. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28921. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28922. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28923. */
  28924. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28925. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28926. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28927. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28928. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28929. };
  28930. /**
  28931. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28932. *
  28933. * @param renderingGroupId The rendering group id corresponding to its index
  28934. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28935. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28936. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28937. */
  28938. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28939. if (depth === void 0) { depth = true; }
  28940. if (stencil === void 0) { stencil = true; }
  28941. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28942. };
  28943. /**
  28944. * Will flag all materials as dirty to trigger new shader compilation
  28945. * @param flag defines the flag used to specify which material part must be marked as dirty
  28946. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28947. */
  28948. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28949. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28950. var material = _a[_i];
  28951. if (predicate && !predicate(material)) {
  28952. continue;
  28953. }
  28954. material.markAsDirty(flag);
  28955. }
  28956. };
  28957. /** @hidden */
  28958. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28959. var _this = this;
  28960. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28961. this._activeRequests.push(request);
  28962. request.onCompleteObservable.add(function (request) {
  28963. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28964. });
  28965. return request;
  28966. };
  28967. /** @hidden */
  28968. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28969. var _this = this;
  28970. return new Promise(function (resolve, reject) {
  28971. _this._loadFile(url, function (data) {
  28972. resolve(data);
  28973. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28974. reject(exception);
  28975. });
  28976. });
  28977. };
  28978. // Statics
  28979. Scene._FOGMODE_NONE = 0;
  28980. Scene._FOGMODE_EXP = 1;
  28981. Scene._FOGMODE_EXP2 = 2;
  28982. Scene._FOGMODE_LINEAR = 3;
  28983. Scene._uniqueIdCounter = 0;
  28984. /**
  28985. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28986. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28987. */
  28988. Scene.MinDeltaTime = 1.0;
  28989. /**
  28990. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28991. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28992. */
  28993. Scene.MaxDeltaTime = 1000.0;
  28994. /** The distance in pixel that you have to move to prevent some events */
  28995. Scene.DragMovementThreshold = 10; // in pixels
  28996. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28997. Scene.LongPressDelay = 500; // in milliseconds
  28998. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28999. Scene.DoubleClickDelay = 300; // in milliseconds
  29000. /** If you need to check double click without raising a single click at first click, enable this flag */
  29001. Scene.ExclusiveDoubleClickMode = false;
  29002. return Scene;
  29003. }());
  29004. BABYLON.Scene = Scene;
  29005. })(BABYLON || (BABYLON = {}));
  29006. //# sourceMappingURL=babylon.scene.js.map
  29007. var BABYLON;
  29008. (function (BABYLON) {
  29009. /**
  29010. * Set of assets to keep when moving a scene into an asset container.
  29011. */
  29012. var KeepAssets = /** @class */ (function () {
  29013. function KeepAssets() {
  29014. /**
  29015. * Cameras to keep.
  29016. */
  29017. this.cameras = new Array();
  29018. /**
  29019. * Lights to keep.
  29020. */
  29021. this.lights = new Array();
  29022. /**
  29023. * Meshes to keep.
  29024. */
  29025. this.meshes = new Array();
  29026. /**
  29027. * Skeletons to keep.
  29028. */
  29029. this.skeletons = new Array();
  29030. /**
  29031. * ParticleSystems to keep.
  29032. */
  29033. this.particleSystems = new Array();
  29034. /**
  29035. * Animations to keep.
  29036. */
  29037. this.animations = new Array();
  29038. /**
  29039. * AnimationGroups to keep.
  29040. */
  29041. this.animationGroups = new Array();
  29042. /**
  29043. * MultiMaterials to keep.
  29044. */
  29045. this.multiMaterials = new Array();
  29046. /**
  29047. * Materials to keep.
  29048. */
  29049. this.materials = new Array();
  29050. /**
  29051. * MorphTargetManagers to keep.
  29052. */
  29053. this.morphTargetManagers = new Array();
  29054. /**
  29055. * Geometries to keep.
  29056. */
  29057. this.geometries = new Array();
  29058. /**
  29059. * TransformNodes to keep.
  29060. */
  29061. this.transformNodes = new Array();
  29062. /**
  29063. * LensFlareSystems to keep.
  29064. */
  29065. this.lensFlareSystems = new Array();
  29066. /**
  29067. * ShadowGenerators to keep.
  29068. */
  29069. this.shadowGenerators = new Array();
  29070. /**
  29071. * ActionManagers to keep.
  29072. */
  29073. this.actionManagers = new Array();
  29074. /**
  29075. * Sounds to keep.
  29076. */
  29077. this.sounds = new Array();
  29078. /**
  29079. * Textures to keep.
  29080. */
  29081. this.textures = new Array();
  29082. /**
  29083. * Effect layers to keep.
  29084. */
  29085. this.effectLayers = new Array();
  29086. }
  29087. return KeepAssets;
  29088. }());
  29089. BABYLON.KeepAssets = KeepAssets;
  29090. /**
  29091. * Container with a set of assets that can be added or removed from a scene.
  29092. */
  29093. var AssetContainer = /** @class */ (function () {
  29094. /**
  29095. * Instantiates an AssetContainer.
  29096. * @param scene The scene the AssetContainer belongs to.
  29097. */
  29098. function AssetContainer(scene) {
  29099. // Objects
  29100. /**
  29101. * Cameras populated in the container.
  29102. */
  29103. this.cameras = new Array();
  29104. /**
  29105. * Lights populated in the container.
  29106. */
  29107. this.lights = new Array();
  29108. /**
  29109. * Meshes populated in the container.
  29110. */
  29111. this.meshes = new Array();
  29112. /**
  29113. * Skeletons populated in the container.
  29114. */
  29115. this.skeletons = new Array();
  29116. /**
  29117. * ParticleSystems populated in the container.
  29118. */
  29119. this.particleSystems = new Array();
  29120. /**
  29121. * Animations populated in the container.
  29122. */
  29123. this.animations = new Array();
  29124. /**
  29125. * AnimationGroups populated in the container.
  29126. */
  29127. this.animationGroups = new Array();
  29128. /**
  29129. * MultiMaterials populated in the container.
  29130. */
  29131. this.multiMaterials = new Array();
  29132. /**
  29133. * Materials populated in the container.
  29134. */
  29135. this.materials = new Array();
  29136. /**
  29137. * MorphTargetManagers populated in the container.
  29138. */
  29139. this.morphTargetManagers = new Array();
  29140. /**
  29141. * Geometries populated in the container.
  29142. */
  29143. this.geometries = new Array();
  29144. /**
  29145. * TransformNodes populated in the container.
  29146. */
  29147. this.transformNodes = new Array();
  29148. /**
  29149. * LensFlareSystems populated in the container.
  29150. */
  29151. this.lensFlareSystems = new Array();
  29152. /**
  29153. * ShadowGenerators populated in the container.
  29154. */
  29155. this.shadowGenerators = new Array();
  29156. /**
  29157. * ActionManagers populated in the container.
  29158. */
  29159. this.actionManagers = new Array();
  29160. /**
  29161. * Sounds populated in the container.
  29162. */
  29163. this.sounds = new Array();
  29164. /**
  29165. * Textures populated in the container.
  29166. */
  29167. this.textures = new Array();
  29168. /**
  29169. * Effect layers populated in the container.
  29170. */
  29171. this.effectLayers = new Array();
  29172. this.scene = scene;
  29173. }
  29174. /**
  29175. * Adds all the assets from the container to the scene.
  29176. */
  29177. AssetContainer.prototype.addAllToScene = function () {
  29178. var _this = this;
  29179. this.cameras.forEach(function (o) {
  29180. _this.scene.addCamera(o);
  29181. });
  29182. this.lights.forEach(function (o) {
  29183. _this.scene.addLight(o);
  29184. });
  29185. this.meshes.forEach(function (o) {
  29186. _this.scene.addMesh(o);
  29187. });
  29188. this.skeletons.forEach(function (o) {
  29189. _this.scene.addSkeleton(o);
  29190. });
  29191. this.particleSystems.forEach(function (o) {
  29192. _this.scene.addParticleSystem(o);
  29193. });
  29194. this.animations.forEach(function (o) {
  29195. _this.scene.addAnimation(o);
  29196. });
  29197. this.animationGroups.forEach(function (o) {
  29198. _this.scene.addAnimationGroup(o);
  29199. });
  29200. this.multiMaterials.forEach(function (o) {
  29201. _this.scene.addMultiMaterial(o);
  29202. });
  29203. this.materials.forEach(function (o) {
  29204. _this.scene.addMaterial(o);
  29205. });
  29206. this.morphTargetManagers.forEach(function (o) {
  29207. _this.scene.addMorphTargetManager(o);
  29208. });
  29209. this.geometries.forEach(function (o) {
  29210. _this.scene.addGeometry(o);
  29211. });
  29212. this.transformNodes.forEach(function (o) {
  29213. _this.scene.addTransformNode(o);
  29214. });
  29215. this.lensFlareSystems.forEach(function (o) {
  29216. _this.scene.addLensFlareSystem(o);
  29217. });
  29218. this.actionManagers.forEach(function (o) {
  29219. _this.scene.addActionManager(o);
  29220. });
  29221. this.sounds.forEach(function (o) {
  29222. o.play();
  29223. o.autoplay = true;
  29224. _this.scene.mainSoundTrack.AddSound(o);
  29225. });
  29226. this.textures.forEach(function (o) {
  29227. _this.scene.addTexture(o);
  29228. });
  29229. this.effectLayers.forEach(function (o) {
  29230. _this.scene.addEffectLayer(o);
  29231. });
  29232. };
  29233. /**
  29234. * Removes all the assets in the container from the scene
  29235. */
  29236. AssetContainer.prototype.removeAllFromScene = function () {
  29237. var _this = this;
  29238. this.cameras.forEach(function (o) {
  29239. _this.scene.removeCamera(o);
  29240. });
  29241. this.lights.forEach(function (o) {
  29242. _this.scene.removeLight(o);
  29243. });
  29244. this.meshes.forEach(function (o) {
  29245. _this.scene.removeMesh(o);
  29246. });
  29247. this.skeletons.forEach(function (o) {
  29248. _this.scene.removeSkeleton(o);
  29249. });
  29250. this.particleSystems.forEach(function (o) {
  29251. _this.scene.removeParticleSystem(o);
  29252. });
  29253. this.animations.forEach(function (o) {
  29254. _this.scene.removeAnimation(o);
  29255. });
  29256. this.animationGroups.forEach(function (o) {
  29257. _this.scene.removeAnimationGroup(o);
  29258. });
  29259. this.multiMaterials.forEach(function (o) {
  29260. _this.scene.removeMultiMaterial(o);
  29261. });
  29262. this.materials.forEach(function (o) {
  29263. _this.scene.removeMaterial(o);
  29264. });
  29265. this.morphTargetManagers.forEach(function (o) {
  29266. _this.scene.removeMorphTargetManager(o);
  29267. });
  29268. this.geometries.forEach(function (o) {
  29269. _this.scene.removeGeometry(o);
  29270. });
  29271. this.transformNodes.forEach(function (o) {
  29272. _this.scene.removeTransformNode(o);
  29273. });
  29274. this.lensFlareSystems.forEach(function (o) {
  29275. _this.scene.removeLensFlareSystem(o);
  29276. });
  29277. this.actionManagers.forEach(function (o) {
  29278. _this.scene.removeActionManager(o);
  29279. });
  29280. this.sounds.forEach(function (o) {
  29281. o.stop();
  29282. o.autoplay = false;
  29283. _this.scene.mainSoundTrack.RemoveSound(o);
  29284. });
  29285. this.textures.forEach(function (o) {
  29286. _this.scene.removeTexture(o);
  29287. });
  29288. this.effectLayers.forEach(function (o) {
  29289. _this.scene.removeEffectLayer(o);
  29290. });
  29291. };
  29292. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29293. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29294. var asset = sourceAssets_1[_i];
  29295. var move = true;
  29296. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29297. var keepAsset = keepAssets_1[_a];
  29298. if (asset === keepAsset) {
  29299. move = false;
  29300. break;
  29301. }
  29302. }
  29303. if (move) {
  29304. targetAssets.push(asset);
  29305. }
  29306. }
  29307. };
  29308. /**
  29309. * Removes all the assets contained in the scene and adds them to the container.
  29310. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29311. */
  29312. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29313. if (keepAssets === undefined) {
  29314. keepAssets = new KeepAssets();
  29315. }
  29316. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29317. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29318. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29319. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29320. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29321. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29322. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29323. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29324. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29325. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29326. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29327. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29328. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29329. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29330. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29331. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29332. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29333. this.removeAllFromScene();
  29334. };
  29335. /**
  29336. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29337. * @returns the root mesh
  29338. */
  29339. AssetContainer.prototype.createRootMesh = function () {
  29340. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29341. this.meshes.forEach(function (m) {
  29342. if (!m.parent) {
  29343. rootMesh.addChild(m);
  29344. }
  29345. });
  29346. this.meshes.unshift(rootMesh);
  29347. return rootMesh;
  29348. };
  29349. return AssetContainer;
  29350. }());
  29351. BABYLON.AssetContainer = AssetContainer;
  29352. })(BABYLON || (BABYLON = {}));
  29353. //# sourceMappingURL=babylon.assetContainer.js.map
  29354. var BABYLON;
  29355. (function (BABYLON) {
  29356. var Buffer = /** @class */ (function () {
  29357. /**
  29358. * Constructor
  29359. * @param engine the engine
  29360. * @param data the data to use for this buffer
  29361. * @param updatable whether the data is updatable
  29362. * @param stride the stride (optional)
  29363. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29364. * @param instanced whether the buffer is instanced (optional)
  29365. * @param useBytes set to true if the stride in in bytes (optional)
  29366. */
  29367. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29368. if (stride === void 0) { stride = 0; }
  29369. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29370. if (instanced === void 0) { instanced = false; }
  29371. if (useBytes === void 0) { useBytes = false; }
  29372. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29373. this._engine = engine.getScene().getEngine();
  29374. }
  29375. else {
  29376. this._engine = engine;
  29377. }
  29378. this._updatable = updatable;
  29379. this._instanced = instanced;
  29380. this._data = data;
  29381. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29382. if (!postponeInternalCreation) { // by default
  29383. this.create();
  29384. }
  29385. }
  29386. /**
  29387. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29388. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29389. * @param offset defines offset in the buffer (0 by default)
  29390. * @param size defines the size in floats of attributes (position is 3 for instance)
  29391. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29392. * @param instanced defines if the vertex buffer contains indexed data
  29393. * @param useBytes defines if the offset and stride are in bytes
  29394. * @returns the new vertex buffer
  29395. */
  29396. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29397. if (useBytes === void 0) { useBytes = false; }
  29398. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29399. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29400. // a lot of these parameters are ignored as they are overriden by the buffer
  29401. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29402. };
  29403. // Properties
  29404. Buffer.prototype.isUpdatable = function () {
  29405. return this._updatable;
  29406. };
  29407. Buffer.prototype.getData = function () {
  29408. return this._data;
  29409. };
  29410. Buffer.prototype.getBuffer = function () {
  29411. return this._buffer;
  29412. };
  29413. /**
  29414. * Gets the stride in float32 units (i.e. byte stride / 4).
  29415. * May not be an integer if the byte stride is not divisible by 4.
  29416. * DEPRECATED. Use byteStride instead.
  29417. * @returns the stride in float32 units
  29418. */
  29419. Buffer.prototype.getStrideSize = function () {
  29420. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29421. };
  29422. // Methods
  29423. Buffer.prototype.create = function (data) {
  29424. if (data === void 0) { data = null; }
  29425. if (!data && this._buffer) {
  29426. return; // nothing to do
  29427. }
  29428. data = data || this._data;
  29429. if (!data) {
  29430. return;
  29431. }
  29432. if (!this._buffer) { // create buffer
  29433. if (this._updatable) {
  29434. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29435. this._data = data;
  29436. }
  29437. else {
  29438. this._buffer = this._engine.createVertexBuffer(data);
  29439. }
  29440. }
  29441. else if (this._updatable) { // update buffer
  29442. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29443. this._data = data;
  29444. }
  29445. };
  29446. Buffer.prototype._rebuild = function () {
  29447. this._buffer = null;
  29448. this.create(this._data);
  29449. };
  29450. Buffer.prototype.update = function (data) {
  29451. this.create(data);
  29452. };
  29453. /**
  29454. * Updates the data directly.
  29455. * @param data the new data
  29456. * @param offset the new offset
  29457. * @param vertexCount the vertex count (optional)
  29458. * @param useBytes set to true if the offset is in bytes
  29459. */
  29460. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29461. if (useBytes === void 0) { useBytes = false; }
  29462. if (!this._buffer) {
  29463. return;
  29464. }
  29465. if (this._updatable) { // update buffer
  29466. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29467. this._data = null;
  29468. }
  29469. };
  29470. Buffer.prototype.dispose = function () {
  29471. if (!this._buffer) {
  29472. return;
  29473. }
  29474. if (this._engine._releaseBuffer(this._buffer)) {
  29475. this._buffer = null;
  29476. }
  29477. };
  29478. return Buffer;
  29479. }());
  29480. BABYLON.Buffer = Buffer;
  29481. })(BABYLON || (BABYLON = {}));
  29482. //# sourceMappingURL=babylon.buffer.js.map
  29483. var BABYLON;
  29484. (function (BABYLON) {
  29485. var VertexBuffer = /** @class */ (function () {
  29486. /**
  29487. * Constructor
  29488. * @param engine the engine
  29489. * @param data the data to use for this vertex buffer
  29490. * @param kind the vertex buffer kind
  29491. * @param updatable whether the data is updatable
  29492. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29493. * @param stride the stride (optional)
  29494. * @param instanced whether the buffer is instanced (optional)
  29495. * @param offset the offset of the data (optional)
  29496. * @param size the number of components (optional)
  29497. * @param type the type of the component (optional)
  29498. * @param normalized whether the data contains normalized data (optional)
  29499. * @param useBytes set to true if stride and offset are in bytes (optional)
  29500. */
  29501. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29502. if (normalized === void 0) { normalized = false; }
  29503. if (useBytes === void 0) { useBytes = false; }
  29504. if (data instanceof BABYLON.Buffer) {
  29505. this._buffer = data;
  29506. this._ownsBuffer = false;
  29507. }
  29508. else {
  29509. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29510. this._ownsBuffer = true;
  29511. }
  29512. this._kind = kind;
  29513. if (type == undefined) {
  29514. var data_1 = this.getData();
  29515. this.type = VertexBuffer.FLOAT;
  29516. if (data_1 instanceof Int8Array)
  29517. this.type = VertexBuffer.BYTE;
  29518. else if (data_1 instanceof Uint8Array)
  29519. this.type = VertexBuffer.UNSIGNED_BYTE;
  29520. else if (data_1 instanceof Int16Array)
  29521. this.type = VertexBuffer.SHORT;
  29522. else if (data_1 instanceof Uint16Array)
  29523. this.type = VertexBuffer.UNSIGNED_SHORT;
  29524. else if (data_1 instanceof Int32Array)
  29525. this.type = VertexBuffer.INT;
  29526. else if (data_1 instanceof Uint32Array)
  29527. this.type = VertexBuffer.UNSIGNED_INT;
  29528. }
  29529. else {
  29530. this.type = type;
  29531. }
  29532. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29533. if (useBytes) {
  29534. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29535. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29536. this.byteOffset = offset || 0;
  29537. }
  29538. else {
  29539. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29540. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29541. this.byteOffset = (offset || 0) * typeByteLength;
  29542. }
  29543. this.normalized = normalized;
  29544. this._instanced = instanced !== undefined ? instanced : false;
  29545. this._instanceDivisor = instanced ? 1 : 0;
  29546. }
  29547. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29548. /**
  29549. * Gets or sets the instance divisor when in instanced mode
  29550. */
  29551. get: function () {
  29552. return this._instanceDivisor;
  29553. },
  29554. set: function (value) {
  29555. this._instanceDivisor = value;
  29556. if (value == 0) {
  29557. this._instanced = false;
  29558. }
  29559. else {
  29560. this._instanced = true;
  29561. }
  29562. },
  29563. enumerable: true,
  29564. configurable: true
  29565. });
  29566. VertexBuffer.prototype._rebuild = function () {
  29567. if (!this._buffer) {
  29568. return;
  29569. }
  29570. this._buffer._rebuild();
  29571. };
  29572. /**
  29573. * Returns the kind of the VertexBuffer (string).
  29574. */
  29575. VertexBuffer.prototype.getKind = function () {
  29576. return this._kind;
  29577. };
  29578. // Properties
  29579. /**
  29580. * Boolean : is the VertexBuffer updatable ?
  29581. */
  29582. VertexBuffer.prototype.isUpdatable = function () {
  29583. return this._buffer.isUpdatable();
  29584. };
  29585. /**
  29586. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29587. */
  29588. VertexBuffer.prototype.getData = function () {
  29589. return this._buffer.getData();
  29590. };
  29591. /**
  29592. * Returns the WebGLBuffer associated to the VertexBuffer.
  29593. */
  29594. VertexBuffer.prototype.getBuffer = function () {
  29595. return this._buffer.getBuffer();
  29596. };
  29597. /**
  29598. * Returns the stride as a multiple of the type byte length.
  29599. * DEPRECATED. Use byteStride instead.
  29600. */
  29601. VertexBuffer.prototype.getStrideSize = function () {
  29602. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29603. };
  29604. /**
  29605. * Returns the offset as a multiple of the type byte length.
  29606. * DEPRECATED. Use byteOffset instead.
  29607. */
  29608. VertexBuffer.prototype.getOffset = function () {
  29609. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29610. };
  29611. /**
  29612. * Returns the number of components per vertex attribute (integer).
  29613. */
  29614. VertexBuffer.prototype.getSize = function () {
  29615. return this._size;
  29616. };
  29617. /**
  29618. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29619. */
  29620. VertexBuffer.prototype.getIsInstanced = function () {
  29621. return this._instanced;
  29622. };
  29623. /**
  29624. * Returns the instancing divisor, zero for non-instanced (integer).
  29625. */
  29626. VertexBuffer.prototype.getInstanceDivisor = function () {
  29627. return this._instanceDivisor;
  29628. };
  29629. // Methods
  29630. /**
  29631. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29632. * Returns the created WebGLBuffer.
  29633. */
  29634. VertexBuffer.prototype.create = function (data) {
  29635. return this._buffer.create(data);
  29636. };
  29637. /**
  29638. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29639. * This function will create a new buffer if the current one is not updatable
  29640. * Returns the updated WebGLBuffer.
  29641. */
  29642. VertexBuffer.prototype.update = function (data) {
  29643. return this._buffer.update(data);
  29644. };
  29645. /**
  29646. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29647. * Returns the directly updated WebGLBuffer.
  29648. * @param data the new data
  29649. * @param offset the new offset
  29650. * @param useBytes set to true if the offset is in bytes
  29651. */
  29652. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29653. if (useBytes === void 0) { useBytes = false; }
  29654. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29655. };
  29656. /**
  29657. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29658. */
  29659. VertexBuffer.prototype.dispose = function () {
  29660. if (this._ownsBuffer) {
  29661. this._buffer.dispose();
  29662. }
  29663. };
  29664. /**
  29665. * Enumerates each value of this vertex buffer as numbers.
  29666. * @param count the number of values to enumerate
  29667. * @param callback the callback function called for each value
  29668. */
  29669. VertexBuffer.prototype.forEach = function (count, callback) {
  29670. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29671. };
  29672. Object.defineProperty(VertexBuffer, "PositionKind", {
  29673. get: function () {
  29674. return VertexBuffer._PositionKind;
  29675. },
  29676. enumerable: true,
  29677. configurable: true
  29678. });
  29679. Object.defineProperty(VertexBuffer, "NormalKind", {
  29680. get: function () {
  29681. return VertexBuffer._NormalKind;
  29682. },
  29683. enumerable: true,
  29684. configurable: true
  29685. });
  29686. Object.defineProperty(VertexBuffer, "TangentKind", {
  29687. get: function () {
  29688. return VertexBuffer._TangentKind;
  29689. },
  29690. enumerable: true,
  29691. configurable: true
  29692. });
  29693. Object.defineProperty(VertexBuffer, "UVKind", {
  29694. get: function () {
  29695. return VertexBuffer._UVKind;
  29696. },
  29697. enumerable: true,
  29698. configurable: true
  29699. });
  29700. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29701. get: function () {
  29702. return VertexBuffer._UV2Kind;
  29703. },
  29704. enumerable: true,
  29705. configurable: true
  29706. });
  29707. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29708. get: function () {
  29709. return VertexBuffer._UV3Kind;
  29710. },
  29711. enumerable: true,
  29712. configurable: true
  29713. });
  29714. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29715. get: function () {
  29716. return VertexBuffer._UV4Kind;
  29717. },
  29718. enumerable: true,
  29719. configurable: true
  29720. });
  29721. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29722. get: function () {
  29723. return VertexBuffer._UV5Kind;
  29724. },
  29725. enumerable: true,
  29726. configurable: true
  29727. });
  29728. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29729. get: function () {
  29730. return VertexBuffer._UV6Kind;
  29731. },
  29732. enumerable: true,
  29733. configurable: true
  29734. });
  29735. Object.defineProperty(VertexBuffer, "ColorKind", {
  29736. get: function () {
  29737. return VertexBuffer._ColorKind;
  29738. },
  29739. enumerable: true,
  29740. configurable: true
  29741. });
  29742. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29743. get: function () {
  29744. return VertexBuffer._MatricesIndicesKind;
  29745. },
  29746. enumerable: true,
  29747. configurable: true
  29748. });
  29749. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29750. get: function () {
  29751. return VertexBuffer._MatricesWeightsKind;
  29752. },
  29753. enumerable: true,
  29754. configurable: true
  29755. });
  29756. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29757. get: function () {
  29758. return VertexBuffer._MatricesIndicesExtraKind;
  29759. },
  29760. enumerable: true,
  29761. configurable: true
  29762. });
  29763. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29764. get: function () {
  29765. return VertexBuffer._MatricesWeightsExtraKind;
  29766. },
  29767. enumerable: true,
  29768. configurable: true
  29769. });
  29770. /**
  29771. * Deduces the stride given a kind.
  29772. * @param kind The kind string to deduce
  29773. * @returns The deduced stride
  29774. */
  29775. VertexBuffer.DeduceStride = function (kind) {
  29776. switch (kind) {
  29777. case VertexBuffer.UVKind:
  29778. case VertexBuffer.UV2Kind:
  29779. case VertexBuffer.UV3Kind:
  29780. case VertexBuffer.UV4Kind:
  29781. case VertexBuffer.UV5Kind:
  29782. case VertexBuffer.UV6Kind:
  29783. return 2;
  29784. case VertexBuffer.NormalKind:
  29785. case VertexBuffer.PositionKind:
  29786. return 3;
  29787. case VertexBuffer.ColorKind:
  29788. case VertexBuffer.MatricesIndicesKind:
  29789. case VertexBuffer.MatricesIndicesExtraKind:
  29790. case VertexBuffer.MatricesWeightsKind:
  29791. case VertexBuffer.MatricesWeightsExtraKind:
  29792. case VertexBuffer.TangentKind:
  29793. return 4;
  29794. default:
  29795. throw new Error("Invalid kind '" + kind + "'");
  29796. }
  29797. };
  29798. /**
  29799. * Gets the byte length of the given type.
  29800. * @param type the type
  29801. * @returns the number of bytes
  29802. */
  29803. VertexBuffer.GetTypeByteLength = function (type) {
  29804. switch (type) {
  29805. case VertexBuffer.BYTE:
  29806. case VertexBuffer.UNSIGNED_BYTE:
  29807. return 1;
  29808. case VertexBuffer.SHORT:
  29809. case VertexBuffer.UNSIGNED_SHORT:
  29810. return 2;
  29811. case VertexBuffer.INT:
  29812. case VertexBuffer.FLOAT:
  29813. return 4;
  29814. default:
  29815. throw new Error("Invalid type '" + type + "'");
  29816. }
  29817. };
  29818. /**
  29819. * Enumerates each value of the given parameters as numbers.
  29820. * @param data the data to enumerate
  29821. * @param byteOffset the byte offset of the data
  29822. * @param byteStride the byte stride of the data
  29823. * @param componentCount the number of components per element
  29824. * @param componentType the type of the component
  29825. * @param count the total number of components
  29826. * @param normalized whether the data is normalized
  29827. * @param callback the callback function called for each value
  29828. */
  29829. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29830. if (data instanceof Array) {
  29831. var offset = byteOffset / 4;
  29832. var stride = byteStride / 4;
  29833. for (var index = 0; index < count; index += componentCount) {
  29834. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29835. callback(data[offset + componentIndex], index + componentIndex);
  29836. }
  29837. offset += stride;
  29838. }
  29839. }
  29840. else {
  29841. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29842. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29843. for (var index = 0; index < count; index += componentCount) {
  29844. var componentByteOffset = byteOffset;
  29845. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29846. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29847. callback(value, index + componentIndex);
  29848. componentByteOffset += componentByteLength;
  29849. }
  29850. byteOffset += byteStride;
  29851. }
  29852. }
  29853. };
  29854. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29855. switch (type) {
  29856. case VertexBuffer.BYTE: {
  29857. var value = dataView.getInt8(byteOffset);
  29858. if (normalized) {
  29859. value = Math.max(value / 127, -1);
  29860. }
  29861. return value;
  29862. }
  29863. case VertexBuffer.UNSIGNED_BYTE: {
  29864. var value = dataView.getUint8(byteOffset);
  29865. if (normalized) {
  29866. value = value / 255;
  29867. }
  29868. return value;
  29869. }
  29870. case VertexBuffer.SHORT: {
  29871. var value = dataView.getInt16(byteOffset, true);
  29872. if (normalized) {
  29873. value = Math.max(value / 16383, -1);
  29874. }
  29875. return value;
  29876. }
  29877. case VertexBuffer.UNSIGNED_SHORT: {
  29878. var value = dataView.getUint16(byteOffset, true);
  29879. if (normalized) {
  29880. value = value / 65535;
  29881. }
  29882. return value;
  29883. }
  29884. case VertexBuffer.FLOAT: {
  29885. return dataView.getFloat32(byteOffset, true);
  29886. }
  29887. default: {
  29888. throw new Error("Invalid component type " + type);
  29889. }
  29890. }
  29891. };
  29892. /**
  29893. * The byte type.
  29894. */
  29895. VertexBuffer.BYTE = 5120;
  29896. /**
  29897. * The unsigned byte type.
  29898. */
  29899. VertexBuffer.UNSIGNED_BYTE = 5121;
  29900. /**
  29901. * The short type.
  29902. */
  29903. VertexBuffer.SHORT = 5122;
  29904. /**
  29905. * The unsigned short type.
  29906. */
  29907. VertexBuffer.UNSIGNED_SHORT = 5123;
  29908. /**
  29909. * The integer type.
  29910. */
  29911. VertexBuffer.INT = 5124;
  29912. /**
  29913. * The unsigned integer type.
  29914. */
  29915. VertexBuffer.UNSIGNED_INT = 5125;
  29916. /**
  29917. * The float type.
  29918. */
  29919. VertexBuffer.FLOAT = 5126;
  29920. // Enums
  29921. VertexBuffer._PositionKind = "position";
  29922. VertexBuffer._NormalKind = "normal";
  29923. VertexBuffer._TangentKind = "tangent";
  29924. VertexBuffer._UVKind = "uv";
  29925. VertexBuffer._UV2Kind = "uv2";
  29926. VertexBuffer._UV3Kind = "uv3";
  29927. VertexBuffer._UV4Kind = "uv4";
  29928. VertexBuffer._UV5Kind = "uv5";
  29929. VertexBuffer._UV6Kind = "uv6";
  29930. VertexBuffer._ColorKind = "color";
  29931. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29932. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29933. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29934. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29935. return VertexBuffer;
  29936. }());
  29937. BABYLON.VertexBuffer = VertexBuffer;
  29938. })(BABYLON || (BABYLON = {}));
  29939. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29940. var BABYLON;
  29941. (function (BABYLON) {
  29942. /**
  29943. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29944. */
  29945. var DummyInternalTextureTracker = /** @class */ (function () {
  29946. function DummyInternalTextureTracker() {
  29947. /**
  29948. * Gets or set the previous tracker in the list
  29949. */
  29950. this.previous = null;
  29951. /**
  29952. * Gets or set the next tracker in the list
  29953. */
  29954. this.next = null;
  29955. }
  29956. return DummyInternalTextureTracker;
  29957. }());
  29958. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29959. })(BABYLON || (BABYLON = {}));
  29960. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29961. var BABYLON;
  29962. (function (BABYLON) {
  29963. /**
  29964. * Class used to store data associated with WebGL texture data for the engine
  29965. * This class should not be used directly
  29966. */
  29967. var InternalTexture = /** @class */ (function () {
  29968. /**
  29969. * Creates a new InternalTexture
  29970. * @param engine defines the engine to use
  29971. * @param dataSource defines the type of data that will be used
  29972. */
  29973. function InternalTexture(engine, dataSource) {
  29974. /**
  29975. * Observable called when the texture is loaded
  29976. */
  29977. this.onLoadedObservable = new BABYLON.Observable();
  29978. /**
  29979. * Gets or set the previous tracker in the list
  29980. */
  29981. this.previous = null;
  29982. /**
  29983. * Gets or set the next tracker in the list
  29984. */
  29985. this.next = null;
  29986. // Private
  29987. /** @hidden */
  29988. this._initialSlot = -1;
  29989. /** @hidden */
  29990. this._designatedSlot = -1;
  29991. /** @hidden */
  29992. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29993. /** @hidden */
  29994. this._comparisonFunction = 0;
  29995. /** @hidden */
  29996. this._references = 1;
  29997. this._engine = engine;
  29998. this._dataSource = dataSource;
  29999. this._webGLTexture = engine._createTexture();
  30000. }
  30001. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30002. /**
  30003. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30004. */
  30005. get: function () {
  30006. return this._dataSource;
  30007. },
  30008. enumerable: true,
  30009. configurable: true
  30010. });
  30011. /**
  30012. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30013. */
  30014. InternalTexture.prototype.incrementReferences = function () {
  30015. this._references++;
  30016. };
  30017. /**
  30018. * Change the size of the texture (not the size of the content)
  30019. * @param width defines the new width
  30020. * @param height defines the new height
  30021. * @param depth defines the new depth (1 by default)
  30022. */
  30023. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30024. if (depth === void 0) { depth = 1; }
  30025. this.width = width;
  30026. this.height = height;
  30027. this.depth = depth;
  30028. this.baseWidth = width;
  30029. this.baseHeight = height;
  30030. this.baseDepth = depth;
  30031. this._size = width * height * depth;
  30032. };
  30033. /** @hidden */
  30034. InternalTexture.prototype._rebuild = function () {
  30035. var _this = this;
  30036. var proxy;
  30037. this.isReady = false;
  30038. this._cachedCoordinatesMode = null;
  30039. this._cachedWrapU = null;
  30040. this._cachedWrapV = null;
  30041. this._cachedAnisotropicFilteringLevel = null;
  30042. switch (this._dataSource) {
  30043. case InternalTexture.DATASOURCE_TEMP:
  30044. return;
  30045. case InternalTexture.DATASOURCE_URL:
  30046. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30047. _this.isReady = true;
  30048. }, null, this._buffer, undefined, this.format);
  30049. proxy._swapAndDie(this);
  30050. return;
  30051. case InternalTexture.DATASOURCE_RAW:
  30052. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30053. proxy._swapAndDie(this);
  30054. this.isReady = true;
  30055. return;
  30056. case InternalTexture.DATASOURCE_RAW3D:
  30057. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30058. proxy._swapAndDie(this);
  30059. this.isReady = true;
  30060. return;
  30061. case InternalTexture.DATASOURCE_DYNAMIC:
  30062. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30063. proxy._swapAndDie(this);
  30064. // The engine will make sure to update content so no need to flag it as isReady = true
  30065. return;
  30066. case InternalTexture.DATASOURCE_RENDERTARGET:
  30067. var options = new BABYLON.RenderTargetCreationOptions();
  30068. options.generateDepthBuffer = this._generateDepthBuffer;
  30069. options.generateMipMaps = this.generateMipMaps;
  30070. options.generateStencilBuffer = this._generateStencilBuffer;
  30071. options.samplingMode = this.samplingMode;
  30072. options.type = this.type;
  30073. if (this.isCube) {
  30074. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30075. }
  30076. else {
  30077. var size = {
  30078. width: this.width,
  30079. height: this.height
  30080. };
  30081. proxy = this._engine.createRenderTargetTexture(size, options);
  30082. }
  30083. proxy._swapAndDie(this);
  30084. this.isReady = true;
  30085. return;
  30086. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30087. var depthTextureOptions = {
  30088. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30089. comparisonFunction: this._comparisonFunction,
  30090. generateStencil: this._generateStencilBuffer,
  30091. isCube: this.isCube
  30092. };
  30093. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30094. proxy._swapAndDie(this);
  30095. this.isReady = true;
  30096. return;
  30097. case InternalTexture.DATASOURCE_CUBE:
  30098. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30099. _this.isReady = true;
  30100. }, null, this.format, this._extension);
  30101. proxy._swapAndDie(this);
  30102. return;
  30103. case InternalTexture.DATASOURCE_CUBERAW:
  30104. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30105. proxy._swapAndDie(this);
  30106. this.isReady = true;
  30107. return;
  30108. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30109. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30110. if (proxy) {
  30111. proxy._swapAndDie(_this);
  30112. }
  30113. _this.isReady = true;
  30114. }, null, this.format, this._extension);
  30115. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30116. return;
  30117. }
  30118. };
  30119. InternalTexture.prototype._swapAndDie = function (target) {
  30120. target._webGLTexture = this._webGLTexture;
  30121. if (this._framebuffer) {
  30122. target._framebuffer = this._framebuffer;
  30123. }
  30124. if (this._depthStencilBuffer) {
  30125. target._depthStencilBuffer = this._depthStencilBuffer;
  30126. }
  30127. if (this._lodTextureHigh) {
  30128. if (target._lodTextureHigh) {
  30129. target._lodTextureHigh.dispose();
  30130. }
  30131. target._lodTextureHigh = this._lodTextureHigh;
  30132. }
  30133. if (this._lodTextureMid) {
  30134. if (target._lodTextureMid) {
  30135. target._lodTextureMid.dispose();
  30136. }
  30137. target._lodTextureMid = this._lodTextureMid;
  30138. }
  30139. if (this._lodTextureLow) {
  30140. if (target._lodTextureLow) {
  30141. target._lodTextureLow.dispose();
  30142. }
  30143. target._lodTextureLow = this._lodTextureLow;
  30144. }
  30145. var cache = this._engine.getLoadedTexturesCache();
  30146. var index = cache.indexOf(this);
  30147. if (index !== -1) {
  30148. cache.splice(index, 1);
  30149. }
  30150. };
  30151. /**
  30152. * Dispose the current allocated resources
  30153. */
  30154. InternalTexture.prototype.dispose = function () {
  30155. if (!this._webGLTexture) {
  30156. return;
  30157. }
  30158. this._references--;
  30159. if (this._references === 0) {
  30160. this._engine._releaseTexture(this);
  30161. this._webGLTexture = null;
  30162. this.previous = null;
  30163. this.next = null;
  30164. }
  30165. };
  30166. /**
  30167. * The source of the texture data is unknown
  30168. */
  30169. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30170. /**
  30171. * Texture data comes from an URL
  30172. */
  30173. InternalTexture.DATASOURCE_URL = 1;
  30174. /**
  30175. * Texture data is only used for temporary storage
  30176. */
  30177. InternalTexture.DATASOURCE_TEMP = 2;
  30178. /**
  30179. * Texture data comes from raw data (ArrayBuffer)
  30180. */
  30181. InternalTexture.DATASOURCE_RAW = 3;
  30182. /**
  30183. * Texture content is dynamic (video or dynamic texture)
  30184. */
  30185. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30186. /**
  30187. * Texture content is generated by rendering to it
  30188. */
  30189. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30190. /**
  30191. * Texture content is part of a multi render target process
  30192. */
  30193. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30194. /**
  30195. * Texture data comes from a cube data file
  30196. */
  30197. InternalTexture.DATASOURCE_CUBE = 7;
  30198. /**
  30199. * Texture data comes from a raw cube data
  30200. */
  30201. InternalTexture.DATASOURCE_CUBERAW = 8;
  30202. /**
  30203. * Texture data come from a prefiltered cube data file
  30204. */
  30205. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30206. /**
  30207. * Texture content is raw 3D data
  30208. */
  30209. InternalTexture.DATASOURCE_RAW3D = 10;
  30210. /**
  30211. * Texture content is a depth texture
  30212. */
  30213. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30214. return InternalTexture;
  30215. }());
  30216. BABYLON.InternalTexture = InternalTexture;
  30217. })(BABYLON || (BABYLON = {}));
  30218. //# sourceMappingURL=babylon.internalTexture.js.map
  30219. var BABYLON;
  30220. (function (BABYLON) {
  30221. var BaseTexture = /** @class */ (function () {
  30222. function BaseTexture(scene) {
  30223. this._hasAlpha = false;
  30224. this.getAlphaFromRGB = false;
  30225. this.level = 1;
  30226. this.coordinatesIndex = 0;
  30227. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30228. /**
  30229. * | Value | Type | Description |
  30230. * | ----- | ------------------ | ----------- |
  30231. * | 0 | CLAMP_ADDRESSMODE | |
  30232. * | 1 | WRAP_ADDRESSMODE | |
  30233. * | 2 | MIRROR_ADDRESSMODE | |
  30234. */
  30235. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30236. /**
  30237. * | Value | Type | Description |
  30238. * | ----- | ------------------ | ----------- |
  30239. * | 0 | CLAMP_ADDRESSMODE | |
  30240. * | 1 | WRAP_ADDRESSMODE | |
  30241. * | 2 | MIRROR_ADDRESSMODE | |
  30242. */
  30243. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30244. /**
  30245. * | Value | Type | Description |
  30246. * | ----- | ------------------ | ----------- |
  30247. * | 0 | CLAMP_ADDRESSMODE | |
  30248. * | 1 | WRAP_ADDRESSMODE | |
  30249. * | 2 | MIRROR_ADDRESSMODE | |
  30250. */
  30251. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30252. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30253. this.isCube = false;
  30254. this.is3D = false;
  30255. this.gammaSpace = true;
  30256. this.invertZ = false;
  30257. this.lodLevelInAlpha = false;
  30258. this.lodGenerationOffset = 0.0;
  30259. this.lodGenerationScale = 0.8;
  30260. this.isRenderTarget = false;
  30261. this.animations = new Array();
  30262. /**
  30263. * An event triggered when the texture is disposed.
  30264. */
  30265. this.onDisposeObservable = new BABYLON.Observable();
  30266. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30267. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30268. if (this._scene) {
  30269. this._scene.textures.push(this);
  30270. }
  30271. this._uid = null;
  30272. }
  30273. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30274. get: function () {
  30275. return this._hasAlpha;
  30276. },
  30277. set: function (value) {
  30278. if (this._hasAlpha === value) {
  30279. return;
  30280. }
  30281. this._hasAlpha = value;
  30282. if (this._scene) {
  30283. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30284. }
  30285. },
  30286. enumerable: true,
  30287. configurable: true
  30288. });
  30289. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30290. get: function () {
  30291. return this._coordinatesMode;
  30292. },
  30293. /**
  30294. * How a texture is mapped.
  30295. *
  30296. * | Value | Type | Description |
  30297. * | ----- | ----------------------------------- | ----------- |
  30298. * | 0 | EXPLICIT_MODE | |
  30299. * | 1 | SPHERICAL_MODE | |
  30300. * | 2 | PLANAR_MODE | |
  30301. * | 3 | CUBIC_MODE | |
  30302. * | 4 | PROJECTION_MODE | |
  30303. * | 5 | SKYBOX_MODE | |
  30304. * | 6 | INVCUBIC_MODE | |
  30305. * | 7 | EQUIRECTANGULAR_MODE | |
  30306. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30307. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30308. */
  30309. set: function (value) {
  30310. if (this._coordinatesMode === value) {
  30311. return;
  30312. }
  30313. this._coordinatesMode = value;
  30314. if (this._scene) {
  30315. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30316. }
  30317. },
  30318. enumerable: true,
  30319. configurable: true
  30320. });
  30321. Object.defineProperty(BaseTexture.prototype, "uid", {
  30322. get: function () {
  30323. if (!this._uid) {
  30324. this._uid = BABYLON.Tools.RandomId();
  30325. }
  30326. return this._uid;
  30327. },
  30328. enumerable: true,
  30329. configurable: true
  30330. });
  30331. BaseTexture.prototype.toString = function () {
  30332. return this.name;
  30333. };
  30334. BaseTexture.prototype.getClassName = function () {
  30335. return "BaseTexture";
  30336. };
  30337. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30338. set: function (callback) {
  30339. if (this._onDisposeObserver) {
  30340. this.onDisposeObservable.remove(this._onDisposeObserver);
  30341. }
  30342. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30343. },
  30344. enumerable: true,
  30345. configurable: true
  30346. });
  30347. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30348. get: function () {
  30349. return true;
  30350. },
  30351. enumerable: true,
  30352. configurable: true
  30353. });
  30354. BaseTexture.prototype.getScene = function () {
  30355. return this._scene;
  30356. };
  30357. BaseTexture.prototype.getTextureMatrix = function () {
  30358. return BABYLON.Matrix.IdentityReadOnly;
  30359. };
  30360. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30361. return BABYLON.Matrix.IdentityReadOnly;
  30362. };
  30363. BaseTexture.prototype.getInternalTexture = function () {
  30364. return this._texture;
  30365. };
  30366. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30367. return !this.isBlocking || this.isReady();
  30368. };
  30369. BaseTexture.prototype.isReady = function () {
  30370. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30371. this.delayLoad();
  30372. return false;
  30373. }
  30374. if (this._texture) {
  30375. return this._texture.isReady;
  30376. }
  30377. return false;
  30378. };
  30379. BaseTexture.prototype.getSize = function () {
  30380. if (this._texture && this._texture.width) {
  30381. return new BABYLON.Size(this._texture.width, this._texture.height);
  30382. }
  30383. if (this._texture && this._texture._size) {
  30384. return new BABYLON.Size(this._texture._size, this._texture._size);
  30385. }
  30386. return BABYLON.Size.Zero();
  30387. };
  30388. BaseTexture.prototype.getBaseSize = function () {
  30389. if (!this.isReady() || !this._texture)
  30390. return BABYLON.Size.Zero();
  30391. if (this._texture._size) {
  30392. return new BABYLON.Size(this._texture._size, this._texture._size);
  30393. }
  30394. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30395. };
  30396. BaseTexture.prototype.scale = function (ratio) {
  30397. };
  30398. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30399. get: function () {
  30400. return false;
  30401. },
  30402. enumerable: true,
  30403. configurable: true
  30404. });
  30405. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30406. if (!this._scene) {
  30407. return null;
  30408. }
  30409. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30410. for (var index = 0; index < texturesCache.length; index++) {
  30411. var texturesCacheEntry = texturesCache[index];
  30412. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30413. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30414. texturesCacheEntry.incrementReferences();
  30415. return texturesCacheEntry;
  30416. }
  30417. }
  30418. }
  30419. return null;
  30420. };
  30421. BaseTexture.prototype._rebuild = function () {
  30422. };
  30423. BaseTexture.prototype.delayLoad = function () {
  30424. };
  30425. BaseTexture.prototype.clone = function () {
  30426. return null;
  30427. };
  30428. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30429. get: function () {
  30430. if (!this._texture) {
  30431. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30432. }
  30433. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30434. },
  30435. enumerable: true,
  30436. configurable: true
  30437. });
  30438. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30439. get: function () {
  30440. if (!this._texture) {
  30441. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30442. }
  30443. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30444. },
  30445. enumerable: true,
  30446. configurable: true
  30447. });
  30448. BaseTexture.prototype.readPixels = function (faceIndex) {
  30449. if (faceIndex === void 0) { faceIndex = 0; }
  30450. if (!this._texture) {
  30451. return null;
  30452. }
  30453. var size = this.getSize();
  30454. var scene = this.getScene();
  30455. if (!scene) {
  30456. return null;
  30457. }
  30458. var engine = scene.getEngine();
  30459. if (this._texture.isCube) {
  30460. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30461. }
  30462. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30463. };
  30464. BaseTexture.prototype.releaseInternalTexture = function () {
  30465. if (this._texture) {
  30466. this._texture.dispose();
  30467. this._texture = null;
  30468. }
  30469. };
  30470. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30471. get: function () {
  30472. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30473. return null;
  30474. }
  30475. if (!this._texture._sphericalPolynomial) {
  30476. this._texture._sphericalPolynomial =
  30477. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30478. }
  30479. return this._texture._sphericalPolynomial;
  30480. },
  30481. set: function (value) {
  30482. if (this._texture) {
  30483. this._texture._sphericalPolynomial = value;
  30484. }
  30485. },
  30486. enumerable: true,
  30487. configurable: true
  30488. });
  30489. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30490. get: function () {
  30491. if (this._texture) {
  30492. return this._texture._lodTextureHigh;
  30493. }
  30494. return null;
  30495. },
  30496. enumerable: true,
  30497. configurable: true
  30498. });
  30499. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30500. get: function () {
  30501. if (this._texture) {
  30502. return this._texture._lodTextureMid;
  30503. }
  30504. return null;
  30505. },
  30506. enumerable: true,
  30507. configurable: true
  30508. });
  30509. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30510. get: function () {
  30511. if (this._texture) {
  30512. return this._texture._lodTextureLow;
  30513. }
  30514. return null;
  30515. },
  30516. enumerable: true,
  30517. configurable: true
  30518. });
  30519. BaseTexture.prototype.dispose = function () {
  30520. if (!this._scene) {
  30521. return;
  30522. }
  30523. // Animations
  30524. this._scene.stopAnimation(this);
  30525. // Remove from scene
  30526. this._scene._removePendingData(this);
  30527. var index = this._scene.textures.indexOf(this);
  30528. if (index >= 0) {
  30529. this._scene.textures.splice(index, 1);
  30530. }
  30531. if (this._texture === undefined) {
  30532. return;
  30533. }
  30534. // Release
  30535. this.releaseInternalTexture();
  30536. // Callback
  30537. this.onDisposeObservable.notifyObservers(this);
  30538. this.onDisposeObservable.clear();
  30539. };
  30540. BaseTexture.prototype.serialize = function () {
  30541. if (!this.name) {
  30542. return null;
  30543. }
  30544. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30545. // Animations
  30546. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30547. return serializationObject;
  30548. };
  30549. BaseTexture.WhenAllReady = function (textures, callback) {
  30550. var numRemaining = textures.length;
  30551. if (numRemaining === 0) {
  30552. callback();
  30553. return;
  30554. }
  30555. var _loop_1 = function () {
  30556. texture = textures[i];
  30557. if (texture.isReady()) {
  30558. if (--numRemaining === 0) {
  30559. callback();
  30560. }
  30561. }
  30562. else {
  30563. onLoadObservable = texture.onLoadObservable;
  30564. var onLoadCallback_1 = function () {
  30565. onLoadObservable.removeCallback(onLoadCallback_1);
  30566. if (--numRemaining === 0) {
  30567. callback();
  30568. }
  30569. };
  30570. onLoadObservable.add(onLoadCallback_1);
  30571. }
  30572. };
  30573. var texture, onLoadObservable;
  30574. for (var i = 0; i < textures.length; i++) {
  30575. _loop_1();
  30576. }
  30577. };
  30578. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30579. __decorate([
  30580. BABYLON.serialize()
  30581. ], BaseTexture.prototype, "name", void 0);
  30582. __decorate([
  30583. BABYLON.serialize("hasAlpha")
  30584. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30585. __decorate([
  30586. BABYLON.serialize()
  30587. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30588. __decorate([
  30589. BABYLON.serialize()
  30590. ], BaseTexture.prototype, "level", void 0);
  30591. __decorate([
  30592. BABYLON.serialize()
  30593. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30594. __decorate([
  30595. BABYLON.serialize("coordinatesMode")
  30596. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30597. __decorate([
  30598. BABYLON.serialize()
  30599. ], BaseTexture.prototype, "wrapU", void 0);
  30600. __decorate([
  30601. BABYLON.serialize()
  30602. ], BaseTexture.prototype, "wrapV", void 0);
  30603. __decorate([
  30604. BABYLON.serialize()
  30605. ], BaseTexture.prototype, "wrapR", void 0);
  30606. __decorate([
  30607. BABYLON.serialize()
  30608. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30609. __decorate([
  30610. BABYLON.serialize()
  30611. ], BaseTexture.prototype, "isCube", void 0);
  30612. __decorate([
  30613. BABYLON.serialize()
  30614. ], BaseTexture.prototype, "is3D", void 0);
  30615. __decorate([
  30616. BABYLON.serialize()
  30617. ], BaseTexture.prototype, "gammaSpace", void 0);
  30618. __decorate([
  30619. BABYLON.serialize()
  30620. ], BaseTexture.prototype, "invertZ", void 0);
  30621. __decorate([
  30622. BABYLON.serialize()
  30623. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30624. __decorate([
  30625. BABYLON.serialize()
  30626. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30627. __decorate([
  30628. BABYLON.serialize()
  30629. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30630. __decorate([
  30631. BABYLON.serialize()
  30632. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30633. return BaseTexture;
  30634. }());
  30635. BABYLON.BaseTexture = BaseTexture;
  30636. })(BABYLON || (BABYLON = {}));
  30637. //# sourceMappingURL=babylon.baseTexture.js.map
  30638. var BABYLON;
  30639. (function (BABYLON) {
  30640. var Texture = /** @class */ (function (_super) {
  30641. __extends(Texture, _super);
  30642. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30643. if (noMipmap === void 0) { noMipmap = false; }
  30644. if (invertY === void 0) { invertY = true; }
  30645. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30646. if (onLoad === void 0) { onLoad = null; }
  30647. if (onError === void 0) { onError = null; }
  30648. if (buffer === void 0) { buffer = null; }
  30649. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30650. var _this = _super.call(this, scene) || this;
  30651. _this.uOffset = 0;
  30652. _this.vOffset = 0;
  30653. _this.uScale = 1.0;
  30654. _this.vScale = 1.0;
  30655. _this.uAng = 0;
  30656. _this.vAng = 0;
  30657. _this.wAng = 0;
  30658. /**
  30659. * Defines the center of rotation (U)
  30660. */
  30661. _this.uRotationCenter = 0.5;
  30662. /**
  30663. * Defines the center of rotation (V)
  30664. */
  30665. _this.vRotationCenter = 0.5;
  30666. /**
  30667. * Defines the center of rotation (W)
  30668. */
  30669. _this.wRotationCenter = 0.5;
  30670. _this._isBlocking = true;
  30671. _this.name = url || "";
  30672. _this.url = url;
  30673. _this._noMipmap = noMipmap;
  30674. _this._invertY = invertY;
  30675. _this._samplingMode = samplingMode;
  30676. _this._buffer = buffer;
  30677. _this._deleteBuffer = deleteBuffer;
  30678. if (format) {
  30679. _this._format = format;
  30680. }
  30681. scene = _this.getScene();
  30682. if (!scene) {
  30683. return _this;
  30684. }
  30685. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30686. var load = function () {
  30687. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30688. _this.onLoadObservable.notifyObservers(_this);
  30689. }
  30690. if (onLoad) {
  30691. onLoad();
  30692. }
  30693. if (!_this.isBlocking && scene) {
  30694. scene.resetCachedMaterial();
  30695. }
  30696. };
  30697. if (!_this.url) {
  30698. _this._delayedOnLoad = load;
  30699. _this._delayedOnError = onError;
  30700. return _this;
  30701. }
  30702. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30703. if (!_this._texture) {
  30704. if (!scene.useDelayedTextureLoading) {
  30705. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30706. if (deleteBuffer) {
  30707. delete _this._buffer;
  30708. }
  30709. }
  30710. else {
  30711. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30712. _this._delayedOnLoad = load;
  30713. _this._delayedOnError = onError;
  30714. }
  30715. }
  30716. else {
  30717. if (_this._texture.isReady) {
  30718. BABYLON.Tools.SetImmediate(function () { return load(); });
  30719. }
  30720. else {
  30721. _this._texture.onLoadedObservable.add(load);
  30722. }
  30723. }
  30724. return _this;
  30725. }
  30726. Object.defineProperty(Texture.prototype, "noMipmap", {
  30727. get: function () {
  30728. return this._noMipmap;
  30729. },
  30730. enumerable: true,
  30731. configurable: true
  30732. });
  30733. Object.defineProperty(Texture.prototype, "isBlocking", {
  30734. get: function () {
  30735. return this._isBlocking;
  30736. },
  30737. set: function (value) {
  30738. this._isBlocking = value;
  30739. },
  30740. enumerable: true,
  30741. configurable: true
  30742. });
  30743. Object.defineProperty(Texture.prototype, "samplingMode", {
  30744. get: function () {
  30745. return this._samplingMode;
  30746. },
  30747. enumerable: true,
  30748. configurable: true
  30749. });
  30750. /**
  30751. * Update the url (and optional buffer) of this texture if url was null during construction.
  30752. * @param url the url of the texture
  30753. * @param buffer the buffer of the texture (defaults to null)
  30754. */
  30755. Texture.prototype.updateURL = function (url, buffer) {
  30756. if (buffer === void 0) { buffer = null; }
  30757. if (this.url) {
  30758. throw new Error("URL is already set");
  30759. }
  30760. this.url = url;
  30761. this._buffer = buffer;
  30762. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30763. this.delayLoad();
  30764. };
  30765. Texture.prototype.delayLoad = function () {
  30766. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30767. return;
  30768. }
  30769. var scene = this.getScene();
  30770. if (!scene) {
  30771. return;
  30772. }
  30773. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30774. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30775. if (!this._texture) {
  30776. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30777. if (this._deleteBuffer) {
  30778. delete this._buffer;
  30779. }
  30780. }
  30781. else {
  30782. if (this._delayedOnLoad) {
  30783. if (this._texture.isReady) {
  30784. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30785. }
  30786. else {
  30787. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30788. }
  30789. }
  30790. }
  30791. this._delayedOnLoad = null;
  30792. this._delayedOnError = null;
  30793. };
  30794. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30795. if (!this._texture) {
  30796. return;
  30797. }
  30798. var scene = this.getScene();
  30799. if (!scene) {
  30800. return;
  30801. }
  30802. this._samplingMode = samplingMode;
  30803. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30804. };
  30805. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30806. x *= this.uScale;
  30807. y *= this.vScale;
  30808. x -= this.uRotationCenter * this.uScale;
  30809. y -= this.vRotationCenter * this.vScale;
  30810. z -= this.wRotationCenter;
  30811. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30812. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30813. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30814. t.z += this.wRotationCenter;
  30815. };
  30816. Texture.prototype.getTextureMatrix = function () {
  30817. var _this = this;
  30818. if (this.uOffset === this._cachedUOffset &&
  30819. this.vOffset === this._cachedVOffset &&
  30820. this.uScale === this._cachedUScale &&
  30821. this.vScale === this._cachedVScale &&
  30822. this.uAng === this._cachedUAng &&
  30823. this.vAng === this._cachedVAng &&
  30824. this.wAng === this._cachedWAng) {
  30825. return this._cachedTextureMatrix;
  30826. }
  30827. this._cachedUOffset = this.uOffset;
  30828. this._cachedVOffset = this.vOffset;
  30829. this._cachedUScale = this.uScale;
  30830. this._cachedVScale = this.vScale;
  30831. this._cachedUAng = this.uAng;
  30832. this._cachedVAng = this.vAng;
  30833. this._cachedWAng = this.wAng;
  30834. if (!this._cachedTextureMatrix) {
  30835. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30836. this._rowGenerationMatrix = new BABYLON.Matrix();
  30837. this._t0 = BABYLON.Vector3.Zero();
  30838. this._t1 = BABYLON.Vector3.Zero();
  30839. this._t2 = BABYLON.Vector3.Zero();
  30840. }
  30841. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30842. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30843. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30844. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30845. this._t1.subtractInPlace(this._t0);
  30846. this._t2.subtractInPlace(this._t0);
  30847. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30848. this._cachedTextureMatrix.m[0] = this._t1.x;
  30849. this._cachedTextureMatrix.m[1] = this._t1.y;
  30850. this._cachedTextureMatrix.m[2] = this._t1.z;
  30851. this._cachedTextureMatrix.m[4] = this._t2.x;
  30852. this._cachedTextureMatrix.m[5] = this._t2.y;
  30853. this._cachedTextureMatrix.m[6] = this._t2.z;
  30854. this._cachedTextureMatrix.m[8] = this._t0.x;
  30855. this._cachedTextureMatrix.m[9] = this._t0.y;
  30856. this._cachedTextureMatrix.m[10] = this._t0.z;
  30857. var scene = this.getScene();
  30858. if (!scene) {
  30859. return this._cachedTextureMatrix;
  30860. }
  30861. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30862. return mat.hasTexture(_this);
  30863. });
  30864. return this._cachedTextureMatrix;
  30865. };
  30866. Texture.prototype.getReflectionTextureMatrix = function () {
  30867. var _this = this;
  30868. var scene = this.getScene();
  30869. if (!scene) {
  30870. return this._cachedTextureMatrix;
  30871. }
  30872. if (this.uOffset === this._cachedUOffset &&
  30873. this.vOffset === this._cachedVOffset &&
  30874. this.uScale === this._cachedUScale &&
  30875. this.vScale === this._cachedVScale &&
  30876. this.coordinatesMode === this._cachedCoordinatesMode) {
  30877. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30878. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30879. return this._cachedTextureMatrix;
  30880. }
  30881. }
  30882. else {
  30883. return this._cachedTextureMatrix;
  30884. }
  30885. }
  30886. if (!this._cachedTextureMatrix) {
  30887. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30888. }
  30889. if (!this._projectionModeMatrix) {
  30890. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30891. }
  30892. this._cachedUOffset = this.uOffset;
  30893. this._cachedVOffset = this.vOffset;
  30894. this._cachedUScale = this.uScale;
  30895. this._cachedVScale = this.vScale;
  30896. this._cachedCoordinatesMode = this.coordinatesMode;
  30897. switch (this.coordinatesMode) {
  30898. case Texture.PLANAR_MODE:
  30899. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30900. this._cachedTextureMatrix[0] = this.uScale;
  30901. this._cachedTextureMatrix[5] = this.vScale;
  30902. this._cachedTextureMatrix[12] = this.uOffset;
  30903. this._cachedTextureMatrix[13] = this.vOffset;
  30904. break;
  30905. case Texture.PROJECTION_MODE:
  30906. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30907. this._projectionModeMatrix.m[0] = 0.5;
  30908. this._projectionModeMatrix.m[5] = -0.5;
  30909. this._projectionModeMatrix.m[10] = 0.0;
  30910. this._projectionModeMatrix.m[12] = 0.5;
  30911. this._projectionModeMatrix.m[13] = 0.5;
  30912. this._projectionModeMatrix.m[14] = 1.0;
  30913. this._projectionModeMatrix.m[15] = 1.0;
  30914. var projectionMatrix = scene.getProjectionMatrix();
  30915. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30916. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30917. break;
  30918. default:
  30919. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30920. break;
  30921. }
  30922. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30923. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30924. });
  30925. return this._cachedTextureMatrix;
  30926. };
  30927. Texture.prototype.clone = function () {
  30928. var _this = this;
  30929. return BABYLON.SerializationHelper.Clone(function () {
  30930. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30931. }, this);
  30932. };
  30933. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30934. get: function () {
  30935. if (!this._onLoadObservable) {
  30936. this._onLoadObservable = new BABYLON.Observable();
  30937. }
  30938. return this._onLoadObservable;
  30939. },
  30940. enumerable: true,
  30941. configurable: true
  30942. });
  30943. Texture.prototype.serialize = function () {
  30944. var serializationObject = _super.prototype.serialize.call(this);
  30945. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30946. serializationObject.base64String = this._buffer;
  30947. serializationObject.name = serializationObject.name.replace("data:", "");
  30948. }
  30949. serializationObject.invertY = this._invertY;
  30950. serializationObject.samplingMode = this.samplingMode;
  30951. return serializationObject;
  30952. };
  30953. Texture.prototype.getClassName = function () {
  30954. return "Texture";
  30955. };
  30956. Texture.prototype.dispose = function () {
  30957. _super.prototype.dispose.call(this);
  30958. if (this.onLoadObservable) {
  30959. this.onLoadObservable.clear();
  30960. this._onLoadObservable = null;
  30961. }
  30962. this._delayedOnLoad = null;
  30963. this._delayedOnError = null;
  30964. };
  30965. // Statics
  30966. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30967. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30968. if (onLoad === void 0) { onLoad = null; }
  30969. if (onError === void 0) { onError = null; }
  30970. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30971. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30972. };
  30973. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30974. if (parsedTexture.customType) {
  30975. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30976. // Update Sampling Mode
  30977. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30978. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30979. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30980. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30981. }
  30982. }
  30983. return parsedCustomTexture;
  30984. }
  30985. if (parsedTexture.isCube) {
  30986. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30987. }
  30988. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30989. return null;
  30990. }
  30991. var texture = BABYLON.SerializationHelper.Parse(function () {
  30992. var generateMipMaps = true;
  30993. if (parsedTexture.noMipmap) {
  30994. generateMipMaps = false;
  30995. }
  30996. if (parsedTexture.mirrorPlane) {
  30997. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30998. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30999. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31000. return mirrorTexture;
  31001. }
  31002. else if (parsedTexture.isRenderTarget) {
  31003. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31004. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31005. return renderTargetTexture;
  31006. }
  31007. else {
  31008. var texture;
  31009. if (parsedTexture.base64String) {
  31010. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31011. }
  31012. else {
  31013. var url = rootUrl + parsedTexture.name;
  31014. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31015. url = parsedTexture.url;
  31016. }
  31017. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31018. }
  31019. return texture;
  31020. }
  31021. }, parsedTexture, scene);
  31022. // Update Sampling Mode
  31023. if (parsedTexture.samplingMode) {
  31024. var sampling = parsedTexture.samplingMode;
  31025. if (texture._samplingMode !== sampling) {
  31026. texture.updateSamplingMode(sampling);
  31027. }
  31028. }
  31029. // Animations
  31030. if (parsedTexture.animations) {
  31031. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31032. var parsedAnimation = parsedTexture.animations[animationIndex];
  31033. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31034. }
  31035. }
  31036. return texture;
  31037. };
  31038. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31039. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31040. if (noMipmap === void 0) { noMipmap = false; }
  31041. if (invertY === void 0) { invertY = true; }
  31042. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31043. if (onLoad === void 0) { onLoad = null; }
  31044. if (onError === void 0) { onError = null; }
  31045. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31046. if (name.substr(0, 5) !== "data:") {
  31047. name = "data:" + name;
  31048. }
  31049. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31050. };
  31051. // Constants
  31052. Texture.NEAREST_SAMPLINGMODE = 1;
  31053. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31054. Texture.BILINEAR_SAMPLINGMODE = 2;
  31055. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31056. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31057. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31058. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31059. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31060. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31061. Texture.NEAREST_LINEAR = 7;
  31062. Texture.NEAREST_NEAREST = 8;
  31063. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31064. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31065. Texture.LINEAR_LINEAR = 11;
  31066. Texture.LINEAR_NEAREST = 12;
  31067. Texture.EXPLICIT_MODE = 0;
  31068. Texture.SPHERICAL_MODE = 1;
  31069. Texture.PLANAR_MODE = 2;
  31070. Texture.CUBIC_MODE = 3;
  31071. Texture.PROJECTION_MODE = 4;
  31072. Texture.SKYBOX_MODE = 5;
  31073. Texture.INVCUBIC_MODE = 6;
  31074. Texture.EQUIRECTANGULAR_MODE = 7;
  31075. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31076. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31077. Texture.CLAMP_ADDRESSMODE = 0;
  31078. Texture.WRAP_ADDRESSMODE = 1;
  31079. Texture.MIRROR_ADDRESSMODE = 2;
  31080. /**
  31081. * 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
  31082. */
  31083. Texture.UseSerializedUrlIfAny = false;
  31084. __decorate([
  31085. BABYLON.serialize()
  31086. ], Texture.prototype, "url", void 0);
  31087. __decorate([
  31088. BABYLON.serialize()
  31089. ], Texture.prototype, "uOffset", void 0);
  31090. __decorate([
  31091. BABYLON.serialize()
  31092. ], Texture.prototype, "vOffset", void 0);
  31093. __decorate([
  31094. BABYLON.serialize()
  31095. ], Texture.prototype, "uScale", void 0);
  31096. __decorate([
  31097. BABYLON.serialize()
  31098. ], Texture.prototype, "vScale", void 0);
  31099. __decorate([
  31100. BABYLON.serialize()
  31101. ], Texture.prototype, "uAng", void 0);
  31102. __decorate([
  31103. BABYLON.serialize()
  31104. ], Texture.prototype, "vAng", void 0);
  31105. __decorate([
  31106. BABYLON.serialize()
  31107. ], Texture.prototype, "wAng", void 0);
  31108. __decorate([
  31109. BABYLON.serialize()
  31110. ], Texture.prototype, "uRotationCenter", void 0);
  31111. __decorate([
  31112. BABYLON.serialize()
  31113. ], Texture.prototype, "vRotationCenter", void 0);
  31114. __decorate([
  31115. BABYLON.serialize()
  31116. ], Texture.prototype, "wRotationCenter", void 0);
  31117. __decorate([
  31118. BABYLON.serialize()
  31119. ], Texture.prototype, "isBlocking", null);
  31120. return Texture;
  31121. }(BABYLON.BaseTexture));
  31122. BABYLON.Texture = Texture;
  31123. })(BABYLON || (BABYLON = {}));
  31124. //# sourceMappingURL=babylon.texture.js.map
  31125. var BABYLON;
  31126. (function (BABYLON) {
  31127. /**
  31128. * @hidden
  31129. **/
  31130. var _InstancesBatch = /** @class */ (function () {
  31131. function _InstancesBatch() {
  31132. this.mustReturn = false;
  31133. this.visibleInstances = new Array();
  31134. this.renderSelf = new Array();
  31135. }
  31136. return _InstancesBatch;
  31137. }());
  31138. BABYLON._InstancesBatch = _InstancesBatch;
  31139. var Mesh = /** @class */ (function (_super) {
  31140. __extends(Mesh, _super);
  31141. /**
  31142. * @constructor
  31143. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31144. * @param {Scene} scene The scene to add this mesh to.
  31145. * @param {Node} parent The parent of this mesh, if it has one
  31146. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31147. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31148. * When false, achieved by calling a clone(), also passing False.
  31149. * This will make creation of children, recursive.
  31150. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31151. */
  31152. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31153. if (scene === void 0) { scene = null; }
  31154. if (parent === void 0) { parent = null; }
  31155. if (source === void 0) { source = null; }
  31156. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31157. var _this = _super.call(this, name, scene) || this;
  31158. // Events
  31159. /**
  31160. * An event triggered before rendering the mesh
  31161. */
  31162. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31163. /**
  31164. * An event triggered after rendering the mesh
  31165. */
  31166. _this.onAfterRenderObservable = new BABYLON.Observable();
  31167. /**
  31168. * An event triggered before drawing the mesh
  31169. */
  31170. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31171. // Members
  31172. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31173. _this.instances = new Array();
  31174. _this._LODLevels = new Array();
  31175. _this._visibleInstances = {};
  31176. _this._renderIdForInstances = new Array();
  31177. _this._batchCache = new _InstancesBatch();
  31178. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31179. // Use by builder only to know what orientation were the mesh build in.
  31180. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31181. _this.overrideMaterialSideOrientation = null;
  31182. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31183. // Will be used to save a source mesh reference, If any
  31184. _this._source = null;
  31185. scene = _this.getScene();
  31186. if (source) {
  31187. // Geometry
  31188. if (source._geometry) {
  31189. source._geometry.applyToMesh(_this);
  31190. }
  31191. // Deep copy
  31192. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31193. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31194. // Source mesh
  31195. _this._source = source;
  31196. // Metadata
  31197. if (source.metadata && source.metadata.clone) {
  31198. _this.metadata = source.metadata.clone();
  31199. }
  31200. else {
  31201. _this.metadata = source.metadata;
  31202. }
  31203. // Tags
  31204. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31205. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31206. }
  31207. // Parent
  31208. _this.parent = source.parent;
  31209. // Pivot
  31210. _this.setPivotMatrix(source.getPivotMatrix());
  31211. _this.id = name + "." + source.id;
  31212. // Material
  31213. _this.material = source.material;
  31214. var index;
  31215. if (!doNotCloneChildren) {
  31216. // Children
  31217. var directDescendants = source.getDescendants(true);
  31218. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31219. var child = directDescendants[index_1];
  31220. if (child.clone) {
  31221. child.clone(name + "." + child.name, _this);
  31222. }
  31223. }
  31224. }
  31225. // Physics clone
  31226. var physicsEngine = _this.getScene().getPhysicsEngine();
  31227. if (clonePhysicsImpostor && physicsEngine) {
  31228. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31229. if (impostor) {
  31230. _this.physicsImpostor = impostor.clone(_this);
  31231. }
  31232. }
  31233. // Particles
  31234. for (index = 0; index < scene.particleSystems.length; index++) {
  31235. var system = scene.particleSystems[index];
  31236. if (system.emitter === source) {
  31237. system.clone(system.name, _this);
  31238. }
  31239. }
  31240. _this.computeWorldMatrix(true);
  31241. }
  31242. // Parent
  31243. if (parent !== null) {
  31244. _this.parent = parent;
  31245. }
  31246. return _this;
  31247. }
  31248. Object.defineProperty(Mesh, "FRONTSIDE", {
  31249. /**
  31250. * Mesh side orientation : usually the external or front surface
  31251. */
  31252. get: function () {
  31253. return Mesh._FRONTSIDE;
  31254. },
  31255. enumerable: true,
  31256. configurable: true
  31257. });
  31258. Object.defineProperty(Mesh, "BACKSIDE", {
  31259. /**
  31260. * Mesh side orientation : usually the internal or back surface
  31261. */
  31262. get: function () {
  31263. return Mesh._BACKSIDE;
  31264. },
  31265. enumerable: true,
  31266. configurable: true
  31267. });
  31268. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31269. /**
  31270. * Mesh side orientation : both internal and external or front and back surfaces
  31271. */
  31272. get: function () {
  31273. return Mesh._DOUBLESIDE;
  31274. },
  31275. enumerable: true,
  31276. configurable: true
  31277. });
  31278. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31279. /**
  31280. * Mesh side orientation : by default, `FRONTSIDE`
  31281. */
  31282. get: function () {
  31283. return Mesh._DEFAULTSIDE;
  31284. },
  31285. enumerable: true,
  31286. configurable: true
  31287. });
  31288. Object.defineProperty(Mesh, "NO_CAP", {
  31289. /**
  31290. * Mesh cap setting : no cap
  31291. */
  31292. get: function () {
  31293. return Mesh._NO_CAP;
  31294. },
  31295. enumerable: true,
  31296. configurable: true
  31297. });
  31298. Object.defineProperty(Mesh, "CAP_START", {
  31299. /**
  31300. * Mesh cap setting : one cap at the beginning of the mesh
  31301. */
  31302. get: function () {
  31303. return Mesh._CAP_START;
  31304. },
  31305. enumerable: true,
  31306. configurable: true
  31307. });
  31308. Object.defineProperty(Mesh, "CAP_END", {
  31309. /**
  31310. * Mesh cap setting : one cap at the end of the mesh
  31311. */
  31312. get: function () {
  31313. return Mesh._CAP_END;
  31314. },
  31315. enumerable: true,
  31316. configurable: true
  31317. });
  31318. Object.defineProperty(Mesh, "CAP_ALL", {
  31319. /**
  31320. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31321. */
  31322. get: function () {
  31323. return Mesh._CAP_ALL;
  31324. },
  31325. enumerable: true,
  31326. configurable: true
  31327. });
  31328. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31329. set: function (callback) {
  31330. if (this._onBeforeDrawObserver) {
  31331. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31332. }
  31333. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31334. },
  31335. enumerable: true,
  31336. configurable: true
  31337. });
  31338. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31339. get: function () {
  31340. return this._morphTargetManager;
  31341. },
  31342. set: function (value) {
  31343. if (this._morphTargetManager === value) {
  31344. return;
  31345. }
  31346. this._morphTargetManager = value;
  31347. this._syncGeometryWithMorphTargetManager();
  31348. },
  31349. enumerable: true,
  31350. configurable: true
  31351. });
  31352. Object.defineProperty(Mesh.prototype, "source", {
  31353. get: function () {
  31354. return this._source;
  31355. },
  31356. enumerable: true,
  31357. configurable: true
  31358. });
  31359. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31360. get: function () {
  31361. return this._unIndexed;
  31362. },
  31363. set: function (value) {
  31364. if (this._unIndexed !== value) {
  31365. this._unIndexed = value;
  31366. this._markSubMeshesAsAttributesDirty();
  31367. }
  31368. },
  31369. enumerable: true,
  31370. configurable: true
  31371. });
  31372. // Methods
  31373. /**
  31374. * Returns the string "Mesh".
  31375. */
  31376. Mesh.prototype.getClassName = function () {
  31377. return "Mesh";
  31378. };
  31379. /**
  31380. * Returns a string.
  31381. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31382. */
  31383. Mesh.prototype.toString = function (fullDetails) {
  31384. var ret = _super.prototype.toString.call(this, fullDetails);
  31385. ret += ", n vertices: " + this.getTotalVertices();
  31386. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31387. if (this.animations) {
  31388. for (var i = 0; i < this.animations.length; i++) {
  31389. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31390. }
  31391. }
  31392. if (fullDetails) {
  31393. if (this._geometry) {
  31394. var ib = this.getIndices();
  31395. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31396. if (vb && ib) {
  31397. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31398. }
  31399. }
  31400. else {
  31401. ret += ", flat shading: UNKNOWN";
  31402. }
  31403. }
  31404. return ret;
  31405. };
  31406. Mesh.prototype._unBindEffect = function () {
  31407. _super.prototype._unBindEffect.call(this);
  31408. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31409. var instance = _a[_i];
  31410. instance._unBindEffect();
  31411. }
  31412. };
  31413. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31414. /**
  31415. * True if the mesh has some Levels Of Details (LOD).
  31416. * Returns a boolean.
  31417. */
  31418. get: function () {
  31419. return this._LODLevels.length > 0;
  31420. },
  31421. enumerable: true,
  31422. configurable: true
  31423. });
  31424. /**
  31425. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31426. * @returns an array of {BABYLON.MeshLODLevel}
  31427. */
  31428. Mesh.prototype.getLODLevels = function () {
  31429. return this._LODLevels;
  31430. };
  31431. Mesh.prototype._sortLODLevels = function () {
  31432. this._LODLevels.sort(function (a, b) {
  31433. if (a.distance < b.distance) {
  31434. return 1;
  31435. }
  31436. if (a.distance > b.distance) {
  31437. return -1;
  31438. }
  31439. return 0;
  31440. });
  31441. };
  31442. /**
  31443. * Add a mesh as LOD level triggered at the given distance.
  31444. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31445. * @param {number} distance The distance from the center of the object to show this level
  31446. * @param {Mesh} mesh The mesh to be added as LOD level
  31447. * @return {Mesh} This mesh (for chaining)
  31448. */
  31449. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31450. if (mesh && mesh._masterMesh) {
  31451. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31452. return this;
  31453. }
  31454. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31455. this._LODLevels.push(level);
  31456. if (mesh) {
  31457. mesh._masterMesh = this;
  31458. }
  31459. this._sortLODLevels();
  31460. return this;
  31461. };
  31462. /**
  31463. * Returns the LOD level mesh at the passed distance or null if not found.
  31464. * It is related to the method `addLODLevel(distance, mesh)`.
  31465. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31466. * Returns an object Mesh or `null`.
  31467. */
  31468. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31469. for (var index = 0; index < this._LODLevels.length; index++) {
  31470. var level = this._LODLevels[index];
  31471. if (level.distance === distance) {
  31472. return level.mesh;
  31473. }
  31474. }
  31475. return null;
  31476. };
  31477. /**
  31478. * Remove a mesh from the LOD array
  31479. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31480. * @param {Mesh} mesh The mesh to be removed.
  31481. * @return {Mesh} This mesh (for chaining)
  31482. */
  31483. Mesh.prototype.removeLODLevel = function (mesh) {
  31484. for (var index = 0; index < this._LODLevels.length; index++) {
  31485. if (this._LODLevels[index].mesh === mesh) {
  31486. this._LODLevels.splice(index, 1);
  31487. if (mesh) {
  31488. mesh._masterMesh = null;
  31489. }
  31490. }
  31491. }
  31492. this._sortLODLevels();
  31493. return this;
  31494. };
  31495. /**
  31496. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31497. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31498. */
  31499. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31500. if (!this._LODLevels || this._LODLevels.length === 0) {
  31501. return this;
  31502. }
  31503. var bSphere;
  31504. if (boundingSphere) {
  31505. bSphere = boundingSphere;
  31506. }
  31507. else {
  31508. var boundingInfo = this.getBoundingInfo();
  31509. bSphere = boundingInfo.boundingSphere;
  31510. }
  31511. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31512. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31513. if (this.onLODLevelSelection) {
  31514. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31515. }
  31516. return this;
  31517. }
  31518. for (var index = 0; index < this._LODLevels.length; index++) {
  31519. var level = this._LODLevels[index];
  31520. if (level.distance < distanceToCamera) {
  31521. if (level.mesh) {
  31522. level.mesh._preActivate();
  31523. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31524. }
  31525. if (this.onLODLevelSelection) {
  31526. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31527. }
  31528. return level.mesh;
  31529. }
  31530. }
  31531. if (this.onLODLevelSelection) {
  31532. this.onLODLevelSelection(distanceToCamera, this, this);
  31533. }
  31534. return this;
  31535. };
  31536. Object.defineProperty(Mesh.prototype, "geometry", {
  31537. /**
  31538. * Returns the mesh internal Geometry object.
  31539. */
  31540. get: function () {
  31541. return this._geometry;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. /**
  31547. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31548. */
  31549. Mesh.prototype.getTotalVertices = function () {
  31550. if (this._geometry === null || this._geometry === undefined) {
  31551. return 0;
  31552. }
  31553. return this._geometry.getTotalVertices();
  31554. };
  31555. /**
  31556. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31557. * 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.
  31558. * You can force the copy with forceCopy === true
  31559. * Returns null if the mesh has no geometry or no vertex buffer.
  31560. * Possible `kind` values :
  31561. * - BABYLON.VertexBuffer.PositionKind
  31562. * - BABYLON.VertexBuffer.UVKind
  31563. * - BABYLON.VertexBuffer.UV2Kind
  31564. * - BABYLON.VertexBuffer.UV3Kind
  31565. * - BABYLON.VertexBuffer.UV4Kind
  31566. * - BABYLON.VertexBuffer.UV5Kind
  31567. * - BABYLON.VertexBuffer.UV6Kind
  31568. * - BABYLON.VertexBuffer.ColorKind
  31569. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31570. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31571. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31572. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31573. */
  31574. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31575. if (!this._geometry) {
  31576. return null;
  31577. }
  31578. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31579. };
  31580. /**
  31581. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31582. * Returns `null` if the mesh has no geometry.
  31583. * Possible `kind` values :
  31584. * - BABYLON.VertexBuffer.PositionKind
  31585. * - BABYLON.VertexBuffer.UVKind
  31586. * - BABYLON.VertexBuffer.UV2Kind
  31587. * - BABYLON.VertexBuffer.UV3Kind
  31588. * - BABYLON.VertexBuffer.UV4Kind
  31589. * - BABYLON.VertexBuffer.UV5Kind
  31590. * - BABYLON.VertexBuffer.UV6Kind
  31591. * - BABYLON.VertexBuffer.ColorKind
  31592. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31593. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31594. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31595. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31596. */
  31597. Mesh.prototype.getVertexBuffer = function (kind) {
  31598. if (!this._geometry) {
  31599. return null;
  31600. }
  31601. return this._geometry.getVertexBuffer(kind);
  31602. };
  31603. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31604. if (!this._geometry) {
  31605. if (this._delayInfo) {
  31606. return this._delayInfo.indexOf(kind) !== -1;
  31607. }
  31608. return false;
  31609. }
  31610. return this._geometry.isVerticesDataPresent(kind);
  31611. };
  31612. /**
  31613. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31614. * Possible `kind` values :
  31615. * - BABYLON.VertexBuffer.PositionKind
  31616. * - BABYLON.VertexBuffer.UVKind
  31617. * - BABYLON.VertexBuffer.UV2Kind
  31618. * - BABYLON.VertexBuffer.UV3Kind
  31619. * - BABYLON.VertexBuffer.UV4Kind
  31620. * - BABYLON.VertexBuffer.UV5Kind
  31621. * - BABYLON.VertexBuffer.UV6Kind
  31622. * - BABYLON.VertexBuffer.ColorKind
  31623. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31624. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31625. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31626. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31627. */
  31628. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31629. if (!this._geometry) {
  31630. if (this._delayInfo) {
  31631. return this._delayInfo.indexOf(kind) !== -1;
  31632. }
  31633. return false;
  31634. }
  31635. return this._geometry.isVertexBufferUpdatable(kind);
  31636. };
  31637. /**
  31638. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31639. * Possible `kind` values :
  31640. * - BABYLON.VertexBuffer.PositionKind
  31641. * - BABYLON.VertexBuffer.UVKind
  31642. * - BABYLON.VertexBuffer.UV2Kind
  31643. * - BABYLON.VertexBuffer.UV3Kind
  31644. * - BABYLON.VertexBuffer.UV4Kind
  31645. * - BABYLON.VertexBuffer.UV5Kind
  31646. * - BABYLON.VertexBuffer.UV6Kind
  31647. * - BABYLON.VertexBuffer.ColorKind
  31648. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31649. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31650. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31651. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31652. */
  31653. Mesh.prototype.getVerticesDataKinds = function () {
  31654. if (!this._geometry) {
  31655. var result = new Array();
  31656. if (this._delayInfo) {
  31657. this._delayInfo.forEach(function (kind, index, array) {
  31658. result.push(kind);
  31659. });
  31660. }
  31661. return result;
  31662. }
  31663. return this._geometry.getVerticesDataKinds();
  31664. };
  31665. /**
  31666. * Returns a positive integer : the total number of indices in this mesh geometry.
  31667. * Returns zero if the mesh has no geometry.
  31668. */
  31669. Mesh.prototype.getTotalIndices = function () {
  31670. if (!this._geometry) {
  31671. return 0;
  31672. }
  31673. return this._geometry.getTotalIndices();
  31674. };
  31675. /**
  31676. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31677. * 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.
  31678. * Returns an empty array if the mesh has no geometry.
  31679. */
  31680. Mesh.prototype.getIndices = function (copyWhenShared) {
  31681. if (!this._geometry) {
  31682. return [];
  31683. }
  31684. return this._geometry.getIndices(copyWhenShared);
  31685. };
  31686. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31687. get: function () {
  31688. return this._masterMesh !== null && this._masterMesh !== undefined;
  31689. },
  31690. enumerable: true,
  31691. configurable: true
  31692. });
  31693. /**
  31694. * Determine if the current mesh is ready to be rendered
  31695. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31696. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31697. * @returns true if all associated assets are ready (material, textures, shaders)
  31698. */
  31699. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31700. if (completeCheck === void 0) { completeCheck = false; }
  31701. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31702. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31703. return false;
  31704. }
  31705. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31706. return false;
  31707. }
  31708. if (!this.subMeshes || this.subMeshes.length === 0) {
  31709. return true;
  31710. }
  31711. if (!completeCheck) {
  31712. return true;
  31713. }
  31714. var engine = this.getEngine();
  31715. var scene = this.getScene();
  31716. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31717. this.computeWorldMatrix();
  31718. var mat = this.material || scene.defaultMaterial;
  31719. if (mat) {
  31720. if (mat.storeEffectOnSubMeshes) {
  31721. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31722. var subMesh = _a[_i];
  31723. var effectiveMaterial = subMesh.getMaterial();
  31724. if (effectiveMaterial) {
  31725. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31726. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31727. return false;
  31728. }
  31729. }
  31730. else {
  31731. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31732. return false;
  31733. }
  31734. }
  31735. }
  31736. }
  31737. }
  31738. else {
  31739. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31740. return false;
  31741. }
  31742. }
  31743. }
  31744. // Shadows
  31745. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31746. var light = _c[_b];
  31747. var generator = light.getShadowGenerator();
  31748. if (generator) {
  31749. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31750. var subMesh = _e[_d];
  31751. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31752. return false;
  31753. }
  31754. }
  31755. }
  31756. }
  31757. // LOD
  31758. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31759. var lod = _g[_f];
  31760. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31761. return false;
  31762. }
  31763. }
  31764. return true;
  31765. };
  31766. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31767. /**
  31768. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31769. * This property is pertinent only for updatable parametric shapes.
  31770. */
  31771. get: function () {
  31772. return this._areNormalsFrozen;
  31773. },
  31774. enumerable: true,
  31775. configurable: true
  31776. });
  31777. /**
  31778. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31779. * It has no effect at all on other shapes.
  31780. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31781. * Returns the Mesh.
  31782. */
  31783. Mesh.prototype.freezeNormals = function () {
  31784. this._areNormalsFrozen = true;
  31785. return this;
  31786. };
  31787. /**
  31788. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31789. * It has no effect at all on other shapes.
  31790. * It reactivates the mesh normals computation if it was previously frozen.
  31791. * Returns the Mesh.
  31792. */
  31793. Mesh.prototype.unfreezeNormals = function () {
  31794. this._areNormalsFrozen = false;
  31795. return this;
  31796. };
  31797. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31798. /**
  31799. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31800. */
  31801. set: function (count) {
  31802. this._overridenInstanceCount = count;
  31803. },
  31804. enumerable: true,
  31805. configurable: true
  31806. });
  31807. // Methods
  31808. Mesh.prototype._preActivate = function () {
  31809. var sceneRenderId = this.getScene().getRenderId();
  31810. if (this._preActivateId === sceneRenderId) {
  31811. return this;
  31812. }
  31813. this._preActivateId = sceneRenderId;
  31814. this._visibleInstances = null;
  31815. return this;
  31816. };
  31817. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31818. if (this._visibleInstances) {
  31819. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31820. }
  31821. return this;
  31822. };
  31823. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31824. if (!this._visibleInstances) {
  31825. this._visibleInstances = {};
  31826. this._visibleInstances.defaultRenderId = renderId;
  31827. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31828. }
  31829. if (!this._visibleInstances[renderId]) {
  31830. this._visibleInstances[renderId] = new Array();
  31831. }
  31832. this._visibleInstances[renderId].push(instance);
  31833. return this;
  31834. };
  31835. /**
  31836. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31837. * This means the mesh underlying bounding box and sphere are recomputed.
  31838. * Returns the Mesh.
  31839. */
  31840. Mesh.prototype.refreshBoundingInfo = function () {
  31841. return this._refreshBoundingInfo(false);
  31842. };
  31843. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31844. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31845. return this;
  31846. }
  31847. var data = this._getPositionData(applySkeleton);
  31848. if (data) {
  31849. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31850. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31851. }
  31852. if (this.subMeshes) {
  31853. for (var index = 0; index < this.subMeshes.length; index++) {
  31854. this.subMeshes[index].refreshBoundingInfo();
  31855. }
  31856. }
  31857. this._updateBoundingInfo();
  31858. return this;
  31859. };
  31860. Mesh.prototype._getPositionData = function (applySkeleton) {
  31861. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31862. if (data && applySkeleton && this.skeleton) {
  31863. data = BABYLON.Tools.Slice(data);
  31864. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31865. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31866. if (matricesWeightsData && matricesIndicesData) {
  31867. var needExtras = this.numBoneInfluencers > 4;
  31868. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31869. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31870. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31871. var tempVector = BABYLON.Tmp.Vector3[0];
  31872. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31873. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31874. var matWeightIdx = 0;
  31875. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31876. finalMatrix.reset();
  31877. var inf;
  31878. var weight;
  31879. for (inf = 0; inf < 4; inf++) {
  31880. weight = matricesWeightsData[matWeightIdx + inf];
  31881. if (weight <= 0)
  31882. break;
  31883. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31884. finalMatrix.addToSelf(tempMatrix);
  31885. }
  31886. if (needExtras) {
  31887. for (inf = 0; inf < 4; inf++) {
  31888. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31889. if (weight <= 0)
  31890. break;
  31891. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31892. finalMatrix.addToSelf(tempMatrix);
  31893. }
  31894. }
  31895. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31896. tempVector.toArray(data, index);
  31897. }
  31898. }
  31899. }
  31900. return data;
  31901. };
  31902. Mesh.prototype._createGlobalSubMesh = function (force) {
  31903. var totalVertices = this.getTotalVertices();
  31904. if (!totalVertices || !this.getIndices()) {
  31905. return null;
  31906. }
  31907. // Check if we need to recreate the submeshes
  31908. if (this.subMeshes && this.subMeshes.length > 0) {
  31909. var ib = this.getIndices();
  31910. if (!ib) {
  31911. return null;
  31912. }
  31913. var totalIndices = ib.length;
  31914. var needToRecreate = false;
  31915. if (force) {
  31916. needToRecreate = true;
  31917. }
  31918. else {
  31919. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31920. var submesh = _a[_i];
  31921. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31922. needToRecreate = true;
  31923. break;
  31924. }
  31925. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31926. needToRecreate = true;
  31927. break;
  31928. }
  31929. }
  31930. }
  31931. if (!needToRecreate) {
  31932. return this.subMeshes[0];
  31933. }
  31934. }
  31935. this.releaseSubMeshes();
  31936. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31937. };
  31938. Mesh.prototype.subdivide = function (count) {
  31939. if (count < 1) {
  31940. return;
  31941. }
  31942. var totalIndices = this.getTotalIndices();
  31943. var subdivisionSize = (totalIndices / count) | 0;
  31944. var offset = 0;
  31945. // Ensure that subdivisionSize is a multiple of 3
  31946. while (subdivisionSize % 3 !== 0) {
  31947. subdivisionSize++;
  31948. }
  31949. this.releaseSubMeshes();
  31950. for (var index = 0; index < count; index++) {
  31951. if (offset >= totalIndices) {
  31952. break;
  31953. }
  31954. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31955. offset += subdivisionSize;
  31956. }
  31957. this.synchronizeInstances();
  31958. };
  31959. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31960. if (updatable === void 0) { updatable = false; }
  31961. if (!this._geometry) {
  31962. var vertexData = new BABYLON.VertexData();
  31963. vertexData.set(data, kind);
  31964. var scene = this.getScene();
  31965. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31966. }
  31967. else {
  31968. this._geometry.setVerticesData(kind, data, updatable, stride);
  31969. }
  31970. return this;
  31971. };
  31972. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31973. if (updatable === void 0) { updatable = true; }
  31974. var vb = this.getVertexBuffer(kind);
  31975. if (!vb || vb.isUpdatable() === updatable) {
  31976. return;
  31977. }
  31978. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31979. };
  31980. /**
  31981. * Sets the mesh VertexBuffer.
  31982. * Returns the Mesh.
  31983. */
  31984. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31985. if (!this._geometry) {
  31986. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31987. }
  31988. this._geometry.setVerticesBuffer(buffer);
  31989. return this;
  31990. };
  31991. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31992. if (!this._geometry) {
  31993. return this;
  31994. }
  31995. if (!makeItUnique) {
  31996. this._geometry.updateVerticesData(kind, data, updateExtends);
  31997. }
  31998. else {
  31999. this.makeGeometryUnique();
  32000. this.updateVerticesData(kind, data, updateExtends, false);
  32001. }
  32002. return this;
  32003. };
  32004. /**
  32005. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32006. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32007. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32008. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32009. * Returns the Mesh.
  32010. */
  32011. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32012. if (computeNormals === void 0) { computeNormals = true; }
  32013. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32014. if (!positions) {
  32015. return this;
  32016. }
  32017. positionFunction(positions);
  32018. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32019. if (computeNormals) {
  32020. var indices = this.getIndices();
  32021. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32022. if (!normals) {
  32023. return this;
  32024. }
  32025. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32026. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32027. }
  32028. return this;
  32029. };
  32030. /**
  32031. * Creates a un-shared specific occurence of the geometry for the mesh.
  32032. * Returns the Mesh.
  32033. */
  32034. Mesh.prototype.makeGeometryUnique = function () {
  32035. if (!this._geometry) {
  32036. return this;
  32037. }
  32038. var oldGeometry = this._geometry;
  32039. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32040. oldGeometry.releaseForMesh(this, true);
  32041. geometry.applyToMesh(this);
  32042. return this;
  32043. };
  32044. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32045. if (totalVertices === void 0) { totalVertices = null; }
  32046. if (updatable === void 0) { updatable = false; }
  32047. if (!this._geometry) {
  32048. var vertexData = new BABYLON.VertexData();
  32049. vertexData.indices = indices;
  32050. var scene = this.getScene();
  32051. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32052. }
  32053. else {
  32054. this._geometry.setIndices(indices, totalVertices, updatable);
  32055. }
  32056. return this;
  32057. };
  32058. /**
  32059. * Update the current index buffer
  32060. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32061. * Returns the Mesh.
  32062. */
  32063. Mesh.prototype.updateIndices = function (indices, offset) {
  32064. if (!this._geometry) {
  32065. return this;
  32066. }
  32067. this._geometry.updateIndices(indices, offset);
  32068. return this;
  32069. };
  32070. /**
  32071. * Invert the geometry to move from a right handed system to a left handed one.
  32072. * Returns the Mesh.
  32073. */
  32074. Mesh.prototype.toLeftHanded = function () {
  32075. if (!this._geometry) {
  32076. return this;
  32077. }
  32078. this._geometry.toLeftHanded();
  32079. return this;
  32080. };
  32081. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32082. if (!this._geometry) {
  32083. return this;
  32084. }
  32085. var engine = this.getScene().getEngine();
  32086. // Wireframe
  32087. var indexToBind;
  32088. if (this._unIndexed) {
  32089. indexToBind = null;
  32090. }
  32091. else {
  32092. switch (fillMode) {
  32093. case BABYLON.Material.PointFillMode:
  32094. indexToBind = null;
  32095. break;
  32096. case BABYLON.Material.WireFrameFillMode:
  32097. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32098. break;
  32099. default:
  32100. case BABYLON.Material.TriangleFillMode:
  32101. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32102. break;
  32103. }
  32104. }
  32105. // VBOs
  32106. this._geometry._bind(effect, indexToBind);
  32107. return this;
  32108. };
  32109. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32110. if (alternate === void 0) { alternate = false; }
  32111. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32112. return this;
  32113. }
  32114. this.onBeforeDrawObservable.notifyObservers(this);
  32115. var scene = this.getScene();
  32116. var engine = scene.getEngine();
  32117. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32118. // or triangles as points
  32119. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32120. }
  32121. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32122. // Triangles as wireframe
  32123. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32124. }
  32125. else {
  32126. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32127. }
  32128. if (scene._isAlternateRenderingEnabled && !alternate) {
  32129. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32130. if (!effect || !scene.activeCamera) {
  32131. return this;
  32132. }
  32133. scene._switchToAlternateCameraConfiguration(true);
  32134. this._effectiveMaterial.bindView(effect);
  32135. this._effectiveMaterial.bindViewProjection(effect);
  32136. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32137. this._draw(subMesh, fillMode, instancesCount, true);
  32138. engine.setViewport(scene.activeCamera.viewport);
  32139. scene._switchToAlternateCameraConfiguration(false);
  32140. this._effectiveMaterial.bindView(effect);
  32141. this._effectiveMaterial.bindViewProjection(effect);
  32142. }
  32143. return this;
  32144. };
  32145. /**
  32146. * Registers for this mesh a javascript function called just before the rendering process.
  32147. * This function is passed the current mesh.
  32148. * Return the Mesh.
  32149. */
  32150. Mesh.prototype.registerBeforeRender = function (func) {
  32151. this.onBeforeRenderObservable.add(func);
  32152. return this;
  32153. };
  32154. /**
  32155. * Disposes a previously registered javascript function called before the rendering.
  32156. * This function is passed the current mesh.
  32157. * Returns the Mesh.
  32158. */
  32159. Mesh.prototype.unregisterBeforeRender = function (func) {
  32160. this.onBeforeRenderObservable.removeCallback(func);
  32161. return this;
  32162. };
  32163. /**
  32164. * Registers for this mesh a javascript function called just after the rendering is complete.
  32165. * This function is passed the current mesh.
  32166. * Returns the Mesh.
  32167. */
  32168. Mesh.prototype.registerAfterRender = function (func) {
  32169. this.onAfterRenderObservable.add(func);
  32170. return this;
  32171. };
  32172. /**
  32173. * Disposes a previously registered javascript function called after the rendering.
  32174. * This function is passed the current mesh.
  32175. * Return the Mesh.
  32176. */
  32177. Mesh.prototype.unregisterAfterRender = function (func) {
  32178. this.onAfterRenderObservable.removeCallback(func);
  32179. return this;
  32180. };
  32181. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32182. var scene = this.getScene();
  32183. this._batchCache.mustReturn = false;
  32184. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32185. this._batchCache.visibleInstances[subMeshId] = null;
  32186. if (this._visibleInstances) {
  32187. var currentRenderId = scene.getRenderId();
  32188. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32189. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32190. var selfRenderId = this._renderId;
  32191. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32192. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32193. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32194. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32195. }
  32196. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32197. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32198. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32199. this._batchCache.mustReturn = true;
  32200. return this._batchCache;
  32201. }
  32202. if (currentRenderId !== selfRenderId) {
  32203. this._batchCache.renderSelf[subMeshId] = false;
  32204. }
  32205. }
  32206. this._renderIdForInstances[subMeshId] = currentRenderId;
  32207. }
  32208. return this._batchCache;
  32209. };
  32210. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32211. var visibleInstances = batch.visibleInstances[subMesh._id];
  32212. if (!visibleInstances) {
  32213. return this;
  32214. }
  32215. var matricesCount = visibleInstances.length + 1;
  32216. var bufferSize = matricesCount * 16 * 4;
  32217. var currentInstancesBufferSize = this._instancesBufferSize;
  32218. var instancesBuffer = this._instancesBuffer;
  32219. while (this._instancesBufferSize < bufferSize) {
  32220. this._instancesBufferSize *= 2;
  32221. }
  32222. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32223. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32224. }
  32225. var offset = 0;
  32226. var instancesCount = 0;
  32227. var world = this.getWorldMatrix();
  32228. if (batch.renderSelf[subMesh._id]) {
  32229. world.copyToArray(this._instancesData, offset);
  32230. offset += 16;
  32231. instancesCount++;
  32232. }
  32233. if (visibleInstances) {
  32234. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32235. var instance = visibleInstances[instanceIndex];
  32236. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32237. offset += 16;
  32238. instancesCount++;
  32239. }
  32240. }
  32241. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32242. if (instancesBuffer) {
  32243. instancesBuffer.dispose();
  32244. }
  32245. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32246. this._instancesBuffer = instancesBuffer;
  32247. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32248. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32249. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32250. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32251. }
  32252. else {
  32253. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32254. }
  32255. this._bind(subMesh, effect, fillMode);
  32256. this._draw(subMesh, fillMode, instancesCount);
  32257. engine.unbindInstanceAttributes();
  32258. return this;
  32259. };
  32260. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32261. var scene = this.getScene();
  32262. var engine = scene.getEngine();
  32263. if (hardwareInstancedRendering) {
  32264. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32265. }
  32266. else {
  32267. if (batch.renderSelf[subMesh._id]) {
  32268. // Draw
  32269. if (onBeforeDraw) {
  32270. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32271. }
  32272. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32273. }
  32274. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32275. if (visibleInstancesForSubMesh) {
  32276. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32277. var instance = visibleInstancesForSubMesh[instanceIndex];
  32278. // World
  32279. var world = instance.getWorldMatrix();
  32280. if (onBeforeDraw) {
  32281. onBeforeDraw(true, world, effectiveMaterial);
  32282. }
  32283. // Draw
  32284. this._draw(subMesh, fillMode);
  32285. }
  32286. }
  32287. }
  32288. return this;
  32289. };
  32290. /**
  32291. * Triggers the draw call for the mesh.
  32292. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32293. * Returns the Mesh.
  32294. */
  32295. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32296. this._checkOcclusionQuery();
  32297. if (this._isOccluded) {
  32298. return this;
  32299. }
  32300. var scene = this.getScene();
  32301. // Managing instances
  32302. var batch = this._getInstancesRenderList(subMesh._id);
  32303. if (batch.mustReturn) {
  32304. return this;
  32305. }
  32306. // Checking geometry state
  32307. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32308. return this;
  32309. }
  32310. this.onBeforeRenderObservable.notifyObservers(this);
  32311. var engine = scene.getEngine();
  32312. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32313. // Material
  32314. var material = subMesh.getMaterial();
  32315. if (!material) {
  32316. return this;
  32317. }
  32318. this._effectiveMaterial = material;
  32319. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32320. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32321. return this;
  32322. }
  32323. }
  32324. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32325. return this;
  32326. }
  32327. // Alpha mode
  32328. if (enableAlphaMode) {
  32329. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32330. }
  32331. // Outline - step 1
  32332. var savedDepthWrite = engine.getDepthWrite();
  32333. if (this.renderOutline) {
  32334. engine.setDepthWrite(false);
  32335. scene.getOutlineRenderer().render(subMesh, batch);
  32336. engine.setDepthWrite(savedDepthWrite);
  32337. }
  32338. var effect;
  32339. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32340. effect = subMesh.effect;
  32341. }
  32342. else {
  32343. effect = this._effectiveMaterial.getEffect();
  32344. }
  32345. if (!effect) {
  32346. return this;
  32347. }
  32348. var sideOrientation = this.overrideMaterialSideOrientation;
  32349. if (sideOrientation == null) {
  32350. sideOrientation = this._effectiveMaterial.sideOrientation;
  32351. if (this._getWorldMatrixDeterminant() < 0) {
  32352. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32353. }
  32354. }
  32355. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32356. if (this._effectiveMaterial.forceDepthWrite) {
  32357. engine.setDepthWrite(true);
  32358. }
  32359. // Bind
  32360. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32361. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32362. this._bind(subMesh, effect, fillMode);
  32363. }
  32364. var world = this.getWorldMatrix();
  32365. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32366. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32367. }
  32368. else {
  32369. this._effectiveMaterial.bind(world, this);
  32370. }
  32371. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32372. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32373. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32374. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32375. }
  32376. // Draw
  32377. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32378. // Unbind
  32379. this._effectiveMaterial.unbind();
  32380. // Outline - step 2
  32381. if (this.renderOutline && savedDepthWrite) {
  32382. engine.setDepthWrite(true);
  32383. engine.setColorWrite(false);
  32384. scene.getOutlineRenderer().render(subMesh, batch);
  32385. engine.setColorWrite(true);
  32386. }
  32387. // Overlay
  32388. if (this.renderOverlay) {
  32389. var currentMode = engine.getAlphaMode();
  32390. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32391. scene.getOutlineRenderer().render(subMesh, batch, true);
  32392. engine.setAlphaMode(currentMode);
  32393. }
  32394. this.onAfterRenderObservable.notifyObservers(this);
  32395. return this;
  32396. };
  32397. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32398. if (isInstance && effectiveMaterial) {
  32399. effectiveMaterial.bindOnlyWorldMatrix(world);
  32400. }
  32401. };
  32402. /**
  32403. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32404. */
  32405. Mesh.prototype.getEmittedParticleSystems = function () {
  32406. var results = new Array();
  32407. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32408. var particleSystem = this.getScene().particleSystems[index];
  32409. if (particleSystem.emitter === this) {
  32410. results.push(particleSystem);
  32411. }
  32412. }
  32413. return results;
  32414. };
  32415. /**
  32416. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32417. */
  32418. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32419. var results = new Array();
  32420. var descendants = this.getDescendants();
  32421. descendants.push(this);
  32422. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32423. var particleSystem = this.getScene().particleSystems[index];
  32424. var emitter = particleSystem.emitter;
  32425. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32426. results.push(particleSystem);
  32427. }
  32428. }
  32429. return results;
  32430. };
  32431. /**
  32432. * Normalize matrix weights so that all vertices have a total weight set to 1
  32433. */
  32434. Mesh.prototype.cleanMatrixWeights = function () {
  32435. var epsilon = 1e-3;
  32436. var noInfluenceBoneIndex = 0.0;
  32437. if (this.skeleton) {
  32438. noInfluenceBoneIndex = this.skeleton.bones.length;
  32439. }
  32440. else {
  32441. return;
  32442. }
  32443. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32444. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32445. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32446. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32447. var influencers = this.numBoneInfluencers;
  32448. var size = matricesWeights.length;
  32449. for (var i = 0; i < size; i += 4) {
  32450. var weight = 0.0;
  32451. var firstZeroWeight = -1;
  32452. for (var j = 0; j < 4; j++) {
  32453. var w = matricesWeights[i + j];
  32454. weight += w;
  32455. if (w < epsilon && firstZeroWeight < 0) {
  32456. firstZeroWeight = j;
  32457. }
  32458. }
  32459. if (matricesWeightsExtra) {
  32460. for (var j = 0; j < 4; j++) {
  32461. var w = matricesWeightsExtra[i + j];
  32462. weight += w;
  32463. if (w < epsilon && firstZeroWeight < 0) {
  32464. firstZeroWeight = j + 4;
  32465. }
  32466. }
  32467. }
  32468. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32469. firstZeroWeight = influencers - 1;
  32470. }
  32471. if (weight > epsilon) {
  32472. var mweight = 1.0 / weight;
  32473. for (var j = 0; j < 4; j++) {
  32474. matricesWeights[i + j] *= mweight;
  32475. }
  32476. if (matricesWeightsExtra) {
  32477. for (var j = 0; j < 4; j++) {
  32478. matricesWeightsExtra[i + j] *= mweight;
  32479. }
  32480. }
  32481. }
  32482. else {
  32483. if (firstZeroWeight >= 4) {
  32484. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32485. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32486. }
  32487. else {
  32488. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32489. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32490. }
  32491. }
  32492. }
  32493. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32494. if (matricesIndicesExtra) {
  32495. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32496. }
  32497. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32498. if (matricesWeightsExtra) {
  32499. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32500. }
  32501. };
  32502. Mesh.prototype._checkDelayState = function () {
  32503. var scene = this.getScene();
  32504. if (this._geometry) {
  32505. this._geometry.load(scene);
  32506. }
  32507. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32508. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32509. this._queueLoad(scene);
  32510. }
  32511. return this;
  32512. };
  32513. Mesh.prototype._queueLoad = function (scene) {
  32514. var _this = this;
  32515. scene._addPendingData(this);
  32516. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32517. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32518. if (data instanceof ArrayBuffer) {
  32519. _this._delayLoadingFunction(data, _this);
  32520. }
  32521. else {
  32522. _this._delayLoadingFunction(JSON.parse(data), _this);
  32523. }
  32524. _this.instances.forEach(function (instance) {
  32525. instance._syncSubMeshes();
  32526. });
  32527. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32528. scene._removePendingData(_this);
  32529. }, function () { }, scene.database, getBinaryData);
  32530. return this;
  32531. };
  32532. /**
  32533. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32534. */
  32535. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32536. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32537. return false;
  32538. }
  32539. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32540. return false;
  32541. }
  32542. this._checkDelayState();
  32543. return true;
  32544. };
  32545. /**
  32546. * Sets the mesh material by the material or multiMaterial `id` property.
  32547. * The material `id` is a string identifying the material or the multiMaterial.
  32548. * This method returns the Mesh.
  32549. */
  32550. Mesh.prototype.setMaterialByID = function (id) {
  32551. var materials = this.getScene().materials;
  32552. var index;
  32553. for (index = materials.length - 1; index > -1; index--) {
  32554. if (materials[index].id === id) {
  32555. this.material = materials[index];
  32556. return this;
  32557. }
  32558. }
  32559. // Multi
  32560. var multiMaterials = this.getScene().multiMaterials;
  32561. for (index = multiMaterials.length - 1; index > -1; index--) {
  32562. if (multiMaterials[index].id === id) {
  32563. this.material = multiMaterials[index];
  32564. return this;
  32565. }
  32566. }
  32567. return this;
  32568. };
  32569. /**
  32570. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32571. */
  32572. Mesh.prototype.getAnimatables = function () {
  32573. var results = new Array();
  32574. if (this.material) {
  32575. results.push(this.material);
  32576. }
  32577. if (this.skeleton) {
  32578. results.push(this.skeleton);
  32579. }
  32580. return results;
  32581. };
  32582. /**
  32583. * Modifies the mesh geometry according to the passed transformation matrix.
  32584. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32585. * The mesh normals are modified accordingly the same transformation.
  32586. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32587. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32588. * Returns the Mesh.
  32589. */
  32590. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32591. // Position
  32592. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32593. return this;
  32594. }
  32595. var submeshes = this.subMeshes.splice(0);
  32596. this._resetPointsArrayCache();
  32597. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32598. var temp = new Array();
  32599. var index;
  32600. for (index = 0; index < data.length; index += 3) {
  32601. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32602. }
  32603. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32604. // Normals
  32605. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32606. return this;
  32607. }
  32608. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32609. temp = [];
  32610. for (index = 0; index < data.length; index += 3) {
  32611. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32612. }
  32613. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32614. // flip faces?
  32615. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32616. this.flipFaces();
  32617. }
  32618. // Restore submeshes
  32619. this.releaseSubMeshes();
  32620. this.subMeshes = submeshes;
  32621. return this;
  32622. };
  32623. /**
  32624. * Modifies the mesh geometry according to its own current World Matrix.
  32625. * The mesh World Matrix is then reset.
  32626. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32627. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32628. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32629. * Returns the Mesh.
  32630. */
  32631. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32632. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32633. this.scaling.copyFromFloats(1, 1, 1);
  32634. this.position.copyFromFloats(0, 0, 0);
  32635. this.rotation.copyFromFloats(0, 0, 0);
  32636. //only if quaternion is already set
  32637. if (this.rotationQuaternion) {
  32638. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32639. }
  32640. this._worldMatrix = BABYLON.Matrix.Identity();
  32641. return this;
  32642. };
  32643. Object.defineProperty(Mesh.prototype, "_positions", {
  32644. // Cache
  32645. get: function () {
  32646. if (this._geometry) {
  32647. return this._geometry._positions;
  32648. }
  32649. return null;
  32650. },
  32651. enumerable: true,
  32652. configurable: true
  32653. });
  32654. Mesh.prototype._resetPointsArrayCache = function () {
  32655. if (this._geometry) {
  32656. this._geometry._resetPointsArrayCache();
  32657. }
  32658. return this;
  32659. };
  32660. Mesh.prototype._generatePointsArray = function () {
  32661. if (this._geometry) {
  32662. return this._geometry._generatePointsArray();
  32663. }
  32664. return false;
  32665. };
  32666. /**
  32667. * Returns a new Mesh object generated from the current mesh properties.
  32668. * This method must not get confused with createInstance().
  32669. * The parameter `name` is a string, the name given to the new mesh.
  32670. * The optional parameter `newParent` can be any Node object (default `null`).
  32671. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32672. * 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.
  32673. */
  32674. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32675. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32676. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32677. };
  32678. /**
  32679. * Releases resources associated with this mesh.
  32680. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32681. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32682. */
  32683. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32684. var _this = this;
  32685. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32686. this.morphTargetManager = null;
  32687. if (this._geometry) {
  32688. this._geometry.releaseForMesh(this, true);
  32689. }
  32690. // Sources
  32691. var meshes = this.getScene().meshes;
  32692. meshes.forEach(function (abstractMesh) {
  32693. var mesh = abstractMesh;
  32694. if (mesh._source && mesh._source === _this) {
  32695. mesh._source = null;
  32696. }
  32697. });
  32698. this._source = null;
  32699. // Instances
  32700. if (this._instancesBuffer) {
  32701. this._instancesBuffer.dispose();
  32702. this._instancesBuffer = null;
  32703. }
  32704. while (this.instances.length) {
  32705. this.instances[0].dispose();
  32706. }
  32707. // Effect layers.
  32708. var effectLayers = this.getScene().effectLayers;
  32709. for (var i = 0; i < effectLayers.length; i++) {
  32710. var effectLayer = effectLayers[i];
  32711. if (effectLayer) {
  32712. effectLayer._disposeMesh(this);
  32713. }
  32714. }
  32715. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32716. };
  32717. /**
  32718. * Modifies the mesh geometry according to a displacement map.
  32719. * 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.
  32720. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32721. * This method returns nothing.
  32722. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32723. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32724. * 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.
  32725. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32726. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32727. *
  32728. * Returns the Mesh.
  32729. */
  32730. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32731. var _this = this;
  32732. var scene = this.getScene();
  32733. var onload = function (img) {
  32734. // Getting height map data
  32735. var canvas = document.createElement("canvas");
  32736. var context = canvas.getContext("2d");
  32737. var heightMapWidth = img.width;
  32738. var heightMapHeight = img.height;
  32739. canvas.width = heightMapWidth;
  32740. canvas.height = heightMapHeight;
  32741. context.drawImage(img, 0, 0);
  32742. // Create VertexData from map data
  32743. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32744. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32745. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32746. //execute success callback, if set
  32747. if (onSuccess) {
  32748. onSuccess(_this);
  32749. }
  32750. };
  32751. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32752. return this;
  32753. };
  32754. /**
  32755. * Modifies the mesh geometry according to a displacementMap buffer.
  32756. * 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.
  32757. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32758. * This method returns nothing.
  32759. * 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.
  32760. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32761. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32762. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32763. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32764. *
  32765. * Returns the Mesh.
  32766. */
  32767. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32768. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32769. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32770. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32771. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32772. return this;
  32773. }
  32774. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32775. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32776. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32777. var position = BABYLON.Vector3.Zero();
  32778. var normal = BABYLON.Vector3.Zero();
  32779. var uv = BABYLON.Vector2.Zero();
  32780. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32781. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32782. for (var index = 0; index < positions.length; index += 3) {
  32783. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32784. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32785. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32786. // Compute height
  32787. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32788. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32789. var pos = (u + v * heightMapWidth) * 4;
  32790. var r = buffer[pos] / 255.0;
  32791. var g = buffer[pos + 1] / 255.0;
  32792. var b = buffer[pos + 2] / 255.0;
  32793. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32794. normal.normalize();
  32795. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32796. position = position.add(normal);
  32797. position.toArray(positions, index);
  32798. }
  32799. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32800. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32801. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32802. return this;
  32803. };
  32804. /**
  32805. * Modify the mesh to get a flat shading rendering.
  32806. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32807. * This method returns the Mesh.
  32808. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32809. */
  32810. Mesh.prototype.convertToFlatShadedMesh = function () {
  32811. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32812. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32813. var kinds = this.getVerticesDataKinds();
  32814. var vbs = {};
  32815. var data = {};
  32816. var newdata = {};
  32817. var updatableNormals = false;
  32818. var kindIndex;
  32819. var kind;
  32820. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32821. kind = kinds[kindIndex];
  32822. var vertexBuffer = this.getVertexBuffer(kind);
  32823. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32824. updatableNormals = vertexBuffer.isUpdatable();
  32825. kinds.splice(kindIndex, 1);
  32826. kindIndex--;
  32827. continue;
  32828. }
  32829. vbs[kind] = vertexBuffer;
  32830. data[kind] = vbs[kind].getData();
  32831. newdata[kind] = [];
  32832. }
  32833. // Save previous submeshes
  32834. var previousSubmeshes = this.subMeshes.slice(0);
  32835. var indices = this.getIndices();
  32836. var totalIndices = this.getTotalIndices();
  32837. // Generating unique vertices per face
  32838. var index;
  32839. for (index = 0; index < totalIndices; index++) {
  32840. var vertexIndex = indices[index];
  32841. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32842. kind = kinds[kindIndex];
  32843. var stride = vbs[kind].getStrideSize();
  32844. for (var offset = 0; offset < stride; offset++) {
  32845. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32846. }
  32847. }
  32848. }
  32849. // Updating faces & normal
  32850. var normals = [];
  32851. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32852. for (index = 0; index < totalIndices; index += 3) {
  32853. indices[index] = index;
  32854. indices[index + 1] = index + 1;
  32855. indices[index + 2] = index + 2;
  32856. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32857. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32858. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32859. var p1p2 = p1.subtract(p2);
  32860. var p3p2 = p3.subtract(p2);
  32861. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32862. // Store same normals for every vertex
  32863. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32864. normals.push(normal.x);
  32865. normals.push(normal.y);
  32866. normals.push(normal.z);
  32867. }
  32868. }
  32869. this.setIndices(indices);
  32870. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32871. // Updating vertex buffers
  32872. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32873. kind = kinds[kindIndex];
  32874. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32875. }
  32876. // Updating submeshes
  32877. this.releaseSubMeshes();
  32878. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32879. var previousOne = previousSubmeshes[submeshIndex];
  32880. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32881. }
  32882. this.synchronizeInstances();
  32883. return this;
  32884. };
  32885. /**
  32886. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32887. * In other words, more vertices, no more indices and a single bigger VBO.
  32888. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32889. * Returns the Mesh.
  32890. */
  32891. Mesh.prototype.convertToUnIndexedMesh = function () {
  32892. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32893. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32894. var kinds = this.getVerticesDataKinds();
  32895. var vbs = {};
  32896. var data = {};
  32897. var newdata = {};
  32898. var kindIndex;
  32899. var kind;
  32900. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32901. kind = kinds[kindIndex];
  32902. var vertexBuffer = this.getVertexBuffer(kind);
  32903. vbs[kind] = vertexBuffer;
  32904. data[kind] = vbs[kind].getData();
  32905. newdata[kind] = [];
  32906. }
  32907. // Save previous submeshes
  32908. var previousSubmeshes = this.subMeshes.slice(0);
  32909. var indices = this.getIndices();
  32910. var totalIndices = this.getTotalIndices();
  32911. // Generating unique vertices per face
  32912. var index;
  32913. for (index = 0; index < totalIndices; index++) {
  32914. var vertexIndex = indices[index];
  32915. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32916. kind = kinds[kindIndex];
  32917. var stride = vbs[kind].getStrideSize();
  32918. for (var offset = 0; offset < stride; offset++) {
  32919. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32920. }
  32921. }
  32922. }
  32923. // Updating indices
  32924. for (index = 0; index < totalIndices; index += 3) {
  32925. indices[index] = index;
  32926. indices[index + 1] = index + 1;
  32927. indices[index + 2] = index + 2;
  32928. }
  32929. this.setIndices(indices);
  32930. // Updating vertex buffers
  32931. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32932. kind = kinds[kindIndex];
  32933. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32934. }
  32935. // Updating submeshes
  32936. this.releaseSubMeshes();
  32937. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32938. var previousOne = previousSubmeshes[submeshIndex];
  32939. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32940. }
  32941. this._unIndexed = true;
  32942. this.synchronizeInstances();
  32943. return this;
  32944. };
  32945. /**
  32946. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32947. * This method returns the Mesh.
  32948. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32949. */
  32950. Mesh.prototype.flipFaces = function (flipNormals) {
  32951. if (flipNormals === void 0) { flipNormals = false; }
  32952. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32953. var i;
  32954. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32955. for (i = 0; i < vertex_data.normals.length; i++) {
  32956. vertex_data.normals[i] *= -1;
  32957. }
  32958. }
  32959. if (vertex_data.indices) {
  32960. var temp;
  32961. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32962. // reassign indices
  32963. temp = vertex_data.indices[i + 1];
  32964. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32965. vertex_data.indices[i + 2] = temp;
  32966. }
  32967. }
  32968. vertex_data.applyToMesh(this);
  32969. return this;
  32970. };
  32971. // Instances
  32972. /**
  32973. * Creates a new InstancedMesh object from the mesh model.
  32974. * An instance shares the same properties and the same material than its model.
  32975. * Only these properties of each instance can then be set individually :
  32976. * - position
  32977. * - rotation
  32978. * - rotationQuaternion
  32979. * - setPivotMatrix
  32980. * - scaling
  32981. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32982. * Warning : this method is not supported for Line mesh and LineSystem
  32983. */
  32984. Mesh.prototype.createInstance = function (name) {
  32985. return new BABYLON.InstancedMesh(name, this);
  32986. };
  32987. /**
  32988. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32989. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32990. * This method returns the Mesh.
  32991. */
  32992. Mesh.prototype.synchronizeInstances = function () {
  32993. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32994. var instance = this.instances[instanceIndex];
  32995. instance._syncSubMeshes();
  32996. }
  32997. return this;
  32998. };
  32999. /**
  33000. * Simplify the mesh according to the given array of settings.
  33001. * Function will return immediately and will simplify async. It returns the Mesh.
  33002. * @param settings a collection of simplification settings.
  33003. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33004. * @param type the type of simplification to run.
  33005. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33006. */
  33007. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33008. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33009. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33010. this.getScene().simplificationQueue.addTask({
  33011. settings: settings,
  33012. parallelProcessing: parallelProcessing,
  33013. mesh: this,
  33014. simplificationType: simplificationType,
  33015. successCallback: successCallback
  33016. });
  33017. return this;
  33018. };
  33019. /**
  33020. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33021. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33022. * This should be used together with the simplification to avoid disappearing triangles.
  33023. * Returns the Mesh.
  33024. * @param successCallback an optional success callback to be called after the optimization finished.
  33025. */
  33026. Mesh.prototype.optimizeIndices = function (successCallback) {
  33027. var _this = this;
  33028. var indices = this.getIndices();
  33029. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33030. if (!positions || !indices) {
  33031. return this;
  33032. }
  33033. var vectorPositions = new Array();
  33034. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33035. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33036. }
  33037. var dupes = new Array();
  33038. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33039. var realPos = vectorPositions.length - 1 - iteration;
  33040. var testedPosition = vectorPositions[realPos];
  33041. for (var j = 0; j < realPos; ++j) {
  33042. var againstPosition = vectorPositions[j];
  33043. if (testedPosition.equals(againstPosition)) {
  33044. dupes[realPos] = j;
  33045. break;
  33046. }
  33047. }
  33048. }, function () {
  33049. for (var i = 0; i < indices.length; ++i) {
  33050. indices[i] = dupes[indices[i]] || indices[i];
  33051. }
  33052. //indices are now reordered
  33053. var originalSubMeshes = _this.subMeshes.slice(0);
  33054. _this.setIndices(indices);
  33055. _this.subMeshes = originalSubMeshes;
  33056. if (successCallback) {
  33057. successCallback(_this);
  33058. }
  33059. });
  33060. return this;
  33061. };
  33062. Mesh.prototype.serialize = function (serializationObject) {
  33063. serializationObject.name = this.name;
  33064. serializationObject.id = this.id;
  33065. serializationObject.type = this.getClassName();
  33066. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33067. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33068. }
  33069. serializationObject.position = this.position.asArray();
  33070. if (this.rotationQuaternion) {
  33071. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33072. }
  33073. else if (this.rotation) {
  33074. serializationObject.rotation = this.rotation.asArray();
  33075. }
  33076. serializationObject.scaling = this.scaling.asArray();
  33077. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33078. serializationObject.isEnabled = this.isEnabled(false);
  33079. serializationObject.isVisible = this.isVisible;
  33080. serializationObject.infiniteDistance = this.infiniteDistance;
  33081. serializationObject.pickable = this.isPickable;
  33082. serializationObject.receiveShadows = this.receiveShadows;
  33083. serializationObject.billboardMode = this.billboardMode;
  33084. serializationObject.visibility = this.visibility;
  33085. serializationObject.checkCollisions = this.checkCollisions;
  33086. serializationObject.isBlocker = this.isBlocker;
  33087. // Parent
  33088. if (this.parent) {
  33089. serializationObject.parentId = this.parent.id;
  33090. }
  33091. // Geometry
  33092. serializationObject.isUnIndexed = this.isUnIndexed;
  33093. var geometry = this._geometry;
  33094. if (geometry) {
  33095. var geometryId = geometry.id;
  33096. serializationObject.geometryId = geometryId;
  33097. // SubMeshes
  33098. serializationObject.subMeshes = [];
  33099. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33100. var subMesh = this.subMeshes[subIndex];
  33101. serializationObject.subMeshes.push({
  33102. materialIndex: subMesh.materialIndex,
  33103. verticesStart: subMesh.verticesStart,
  33104. verticesCount: subMesh.verticesCount,
  33105. indexStart: subMesh.indexStart,
  33106. indexCount: subMesh.indexCount
  33107. });
  33108. }
  33109. }
  33110. // Material
  33111. if (this.material) {
  33112. serializationObject.materialId = this.material.id;
  33113. }
  33114. else {
  33115. this.material = null;
  33116. }
  33117. // Morph targets
  33118. if (this.morphTargetManager) {
  33119. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33120. }
  33121. // Skeleton
  33122. if (this.skeleton) {
  33123. serializationObject.skeletonId = this.skeleton.id;
  33124. }
  33125. // Physics
  33126. //TODO implement correct serialization for physics impostors.
  33127. var impostor = this.getPhysicsImpostor();
  33128. if (impostor) {
  33129. serializationObject.physicsMass = impostor.getParam("mass");
  33130. serializationObject.physicsFriction = impostor.getParam("friction");
  33131. serializationObject.physicsRestitution = impostor.getParam("mass");
  33132. serializationObject.physicsImpostor = impostor.type;
  33133. }
  33134. // Metadata
  33135. if (this.metadata) {
  33136. serializationObject.metadata = this.metadata;
  33137. }
  33138. // Instances
  33139. serializationObject.instances = [];
  33140. for (var index = 0; index < this.instances.length; index++) {
  33141. var instance = this.instances[index];
  33142. var serializationInstance = {
  33143. name: instance.name,
  33144. id: instance.id,
  33145. position: instance.position.asArray(),
  33146. scaling: instance.scaling.asArray()
  33147. };
  33148. if (instance.rotationQuaternion) {
  33149. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33150. }
  33151. else if (instance.rotation) {
  33152. serializationInstance.rotation = instance.rotation.asArray();
  33153. }
  33154. serializationObject.instances.push(serializationInstance);
  33155. // Animations
  33156. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33157. serializationInstance.ranges = instance.serializeAnimationRanges();
  33158. }
  33159. //
  33160. // Animations
  33161. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33162. serializationObject.ranges = this.serializeAnimationRanges();
  33163. // Layer mask
  33164. serializationObject.layerMask = this.layerMask;
  33165. // Alpha
  33166. serializationObject.alphaIndex = this.alphaIndex;
  33167. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33168. // Overlay
  33169. serializationObject.overlayAlpha = this.overlayAlpha;
  33170. serializationObject.overlayColor = this.overlayColor.asArray();
  33171. serializationObject.renderOverlay = this.renderOverlay;
  33172. // Fog
  33173. serializationObject.applyFog = this.applyFog;
  33174. // Action Manager
  33175. if (this.actionManager) {
  33176. serializationObject.actions = this.actionManager.serialize(this.name);
  33177. }
  33178. };
  33179. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33180. if (!this.geometry) {
  33181. return;
  33182. }
  33183. this._markSubMeshesAsAttributesDirty();
  33184. var morphTargetManager = this._morphTargetManager;
  33185. if (morphTargetManager && morphTargetManager.vertexCount) {
  33186. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33187. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33188. this.morphTargetManager = null;
  33189. return;
  33190. }
  33191. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33192. var morphTarget = morphTargetManager.getActiveTarget(index);
  33193. var positions = morphTarget.getPositions();
  33194. if (!positions) {
  33195. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33196. return;
  33197. }
  33198. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33199. var normals = morphTarget.getNormals();
  33200. if (normals) {
  33201. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33202. }
  33203. var tangents = morphTarget.getTangents();
  33204. if (tangents) {
  33205. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33206. }
  33207. }
  33208. }
  33209. else {
  33210. var index = 0;
  33211. // Positions
  33212. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33213. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33214. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33215. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33216. }
  33217. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33218. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33219. }
  33220. index++;
  33221. }
  33222. }
  33223. };
  33224. // Statics
  33225. /**
  33226. * Returns a new Mesh object parsed from the source provided.
  33227. * The parameter `parsedMesh` is the source.
  33228. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33229. */
  33230. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33231. var mesh;
  33232. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33233. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33234. }
  33235. else {
  33236. mesh = new Mesh(parsedMesh.name, scene);
  33237. }
  33238. mesh.id = parsedMesh.id;
  33239. if (BABYLON.Tags) {
  33240. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33241. }
  33242. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33243. if (parsedMesh.metadata !== undefined) {
  33244. mesh.metadata = parsedMesh.metadata;
  33245. }
  33246. if (parsedMesh.rotationQuaternion) {
  33247. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33248. }
  33249. else if (parsedMesh.rotation) {
  33250. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33251. }
  33252. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33253. if (parsedMesh.localMatrix) {
  33254. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33255. }
  33256. else if (parsedMesh.pivotMatrix) {
  33257. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33258. }
  33259. mesh.setEnabled(parsedMesh.isEnabled);
  33260. mesh.isVisible = parsedMesh.isVisible;
  33261. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33262. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33263. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33264. if (parsedMesh.applyFog !== undefined) {
  33265. mesh.applyFog = parsedMesh.applyFog;
  33266. }
  33267. if (parsedMesh.pickable !== undefined) {
  33268. mesh.isPickable = parsedMesh.pickable;
  33269. }
  33270. if (parsedMesh.alphaIndex !== undefined) {
  33271. mesh.alphaIndex = parsedMesh.alphaIndex;
  33272. }
  33273. mesh.receiveShadows = parsedMesh.receiveShadows;
  33274. mesh.billboardMode = parsedMesh.billboardMode;
  33275. if (parsedMesh.visibility !== undefined) {
  33276. mesh.visibility = parsedMesh.visibility;
  33277. }
  33278. mesh.checkCollisions = parsedMesh.checkCollisions;
  33279. if (parsedMesh.isBlocker !== undefined) {
  33280. mesh.isBlocker = parsedMesh.isBlocker;
  33281. }
  33282. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33283. // freezeWorldMatrix
  33284. if (parsedMesh.freezeWorldMatrix) {
  33285. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33286. }
  33287. // Parent
  33288. if (parsedMesh.parentId) {
  33289. mesh._waitingParentId = parsedMesh.parentId;
  33290. }
  33291. // Actions
  33292. if (parsedMesh.actions !== undefined) {
  33293. mesh._waitingActions = parsedMesh.actions;
  33294. }
  33295. // Overlay
  33296. if (parsedMesh.overlayAlpha !== undefined) {
  33297. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33298. }
  33299. if (parsedMesh.overlayColor !== undefined) {
  33300. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33301. }
  33302. if (parsedMesh.renderOverlay !== undefined) {
  33303. mesh.renderOverlay = parsedMesh.renderOverlay;
  33304. }
  33305. // Geometry
  33306. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33307. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33308. if (parsedMesh.delayLoadingFile) {
  33309. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33310. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33311. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33312. if (parsedMesh._binaryInfo) {
  33313. mesh._binaryInfo = parsedMesh._binaryInfo;
  33314. }
  33315. mesh._delayInfo = [];
  33316. if (parsedMesh.hasUVs) {
  33317. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33318. }
  33319. if (parsedMesh.hasUVs2) {
  33320. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33321. }
  33322. if (parsedMesh.hasUVs3) {
  33323. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33324. }
  33325. if (parsedMesh.hasUVs4) {
  33326. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33327. }
  33328. if (parsedMesh.hasUVs5) {
  33329. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33330. }
  33331. if (parsedMesh.hasUVs6) {
  33332. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33333. }
  33334. if (parsedMesh.hasColors) {
  33335. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33336. }
  33337. if (parsedMesh.hasMatricesIndices) {
  33338. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33339. }
  33340. if (parsedMesh.hasMatricesWeights) {
  33341. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33342. }
  33343. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33344. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33345. mesh._checkDelayState();
  33346. }
  33347. }
  33348. else {
  33349. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33350. }
  33351. // Material
  33352. if (parsedMesh.materialId) {
  33353. mesh.setMaterialByID(parsedMesh.materialId);
  33354. }
  33355. else {
  33356. mesh.material = null;
  33357. }
  33358. // Morph targets
  33359. if (parsedMesh.morphTargetManagerId > -1) {
  33360. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33361. }
  33362. // Skeleton
  33363. if (parsedMesh.skeletonId > -1) {
  33364. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33365. if (parsedMesh.numBoneInfluencers) {
  33366. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33367. }
  33368. }
  33369. // Animations
  33370. if (parsedMesh.animations) {
  33371. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33372. var parsedAnimation = parsedMesh.animations[animationIndex];
  33373. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33374. }
  33375. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33376. }
  33377. if (parsedMesh.autoAnimate) {
  33378. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33379. }
  33380. // Layer Mask
  33381. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33382. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33383. }
  33384. else {
  33385. mesh.layerMask = 0x0FFFFFFF;
  33386. }
  33387. // Physics
  33388. if (parsedMesh.physicsImpostor) {
  33389. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33390. mass: parsedMesh.physicsMass,
  33391. friction: parsedMesh.physicsFriction,
  33392. restitution: parsedMesh.physicsRestitution
  33393. }, scene);
  33394. }
  33395. // Instances
  33396. if (parsedMesh.instances) {
  33397. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33398. var parsedInstance = parsedMesh.instances[index];
  33399. var instance = mesh.createInstance(parsedInstance.name);
  33400. if (parsedInstance.id) {
  33401. instance.id = parsedInstance.id;
  33402. }
  33403. if (BABYLON.Tags) {
  33404. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33405. }
  33406. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33407. if (parsedInstance.parentId) {
  33408. instance._waitingParentId = parsedInstance.parentId;
  33409. }
  33410. if (parsedInstance.rotationQuaternion) {
  33411. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33412. }
  33413. else if (parsedInstance.rotation) {
  33414. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33415. }
  33416. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33417. instance.checkCollisions = mesh.checkCollisions;
  33418. if (parsedMesh.animations) {
  33419. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33420. parsedAnimation = parsedMesh.animations[animationIndex];
  33421. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33422. }
  33423. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33424. }
  33425. }
  33426. }
  33427. return mesh;
  33428. };
  33429. /**
  33430. * Creates a ribbon mesh.
  33431. * Please consider using the same method from the MeshBuilder class instead.
  33432. * 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.
  33433. *
  33434. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33435. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33436. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33437. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33438. * 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.
  33439. * 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.
  33440. * 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
  33441. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33442. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33443. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33444. */
  33445. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33446. if (closeArray === void 0) { closeArray = false; }
  33447. if (updatable === void 0) { updatable = false; }
  33448. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33449. pathArray: pathArray,
  33450. closeArray: closeArray,
  33451. closePath: closePath,
  33452. offset: offset,
  33453. updatable: updatable,
  33454. sideOrientation: sideOrientation,
  33455. instance: instance
  33456. }, scene);
  33457. };
  33458. /**
  33459. * Creates a plane polygonal mesh. By default, this is a disc.
  33460. * Please consider using the same method from the MeshBuilder class instead.
  33461. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33462. * 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.
  33463. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33464. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33466. */
  33467. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33468. if (scene === void 0) { scene = null; }
  33469. var options = {
  33470. radius: radius,
  33471. tessellation: tessellation,
  33472. sideOrientation: sideOrientation,
  33473. updatable: updatable
  33474. };
  33475. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33476. };
  33477. /**
  33478. * Creates a box mesh.
  33479. * Please consider using the same method from the MeshBuilder class instead.
  33480. * The parameter `size` sets the size (float) of each box side (default 1).
  33481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33482. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33484. */
  33485. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33486. if (scene === void 0) { scene = null; }
  33487. var options = {
  33488. size: size,
  33489. sideOrientation: sideOrientation,
  33490. updatable: updatable
  33491. };
  33492. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33493. };
  33494. /**
  33495. * Creates a sphere mesh.
  33496. * Please consider using the same method from the MeshBuilder class instead.
  33497. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33498. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33499. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33500. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33502. */
  33503. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33504. var options = {
  33505. segments: segments,
  33506. diameterX: diameter,
  33507. diameterY: diameter,
  33508. diameterZ: diameter,
  33509. sideOrientation: sideOrientation,
  33510. updatable: updatable
  33511. };
  33512. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33513. };
  33514. /**
  33515. * Creates a cylinder or a cone mesh.
  33516. * Please consider using the same method from the MeshBuilder class instead.
  33517. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33518. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33519. * 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.
  33520. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33521. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33522. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33523. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33524. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33525. */
  33526. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33527. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33528. if (scene !== undefined) {
  33529. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33530. updatable = scene;
  33531. }
  33532. scene = subdivisions;
  33533. subdivisions = 1;
  33534. }
  33535. var options = {
  33536. height: height,
  33537. diameterTop: diameterTop,
  33538. diameterBottom: diameterBottom,
  33539. tessellation: tessellation,
  33540. subdivisions: subdivisions,
  33541. sideOrientation: sideOrientation,
  33542. updatable: updatable
  33543. };
  33544. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33545. };
  33546. // Torus (Code from SharpDX.org)
  33547. /**
  33548. * Creates a torus mesh.
  33549. * Please consider using the same method from the MeshBuilder class instead.
  33550. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33551. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33552. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33554. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33556. */
  33557. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33558. var options = {
  33559. diameter: diameter,
  33560. thickness: thickness,
  33561. tessellation: tessellation,
  33562. sideOrientation: sideOrientation,
  33563. updatable: updatable
  33564. };
  33565. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33566. };
  33567. /**
  33568. * Creates a torus knot mesh.
  33569. * Please consider using the same method from the MeshBuilder class instead.
  33570. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33571. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33572. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33573. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33574. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33575. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33577. */
  33578. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33579. var options = {
  33580. radius: radius,
  33581. tube: tube,
  33582. radialSegments: radialSegments,
  33583. tubularSegments: tubularSegments,
  33584. p: p,
  33585. q: q,
  33586. sideOrientation: sideOrientation,
  33587. updatable: updatable
  33588. };
  33589. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33590. };
  33591. /**
  33592. * Creates a line mesh.
  33593. * Please consider using the same method from the MeshBuilder class instead.
  33594. * 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.
  33595. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33596. * The parameter `points` is an array successive Vector3.
  33597. * 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
  33598. * When updating an instance, remember that only point positions can change, not the number of points.
  33599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33600. */
  33601. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33602. if (scene === void 0) { scene = null; }
  33603. if (updatable === void 0) { updatable = false; }
  33604. if (instance === void 0) { instance = null; }
  33605. var options = {
  33606. points: points,
  33607. updatable: updatable,
  33608. instance: instance
  33609. };
  33610. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33611. };
  33612. /**
  33613. * Creates a dashed line mesh.
  33614. * Please consider using the same method from the MeshBuilder class instead.
  33615. * 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.
  33616. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33617. * The parameter `points` is an array successive Vector3.
  33618. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33619. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33620. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33621. * 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
  33622. * When updating an instance, remember that only point positions can change, not the number of points.
  33623. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33624. */
  33625. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33626. if (scene === void 0) { scene = null; }
  33627. var options = {
  33628. points: points,
  33629. dashSize: dashSize,
  33630. gapSize: gapSize,
  33631. dashNb: dashNb,
  33632. updatable: updatable,
  33633. instance: instance
  33634. };
  33635. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33636. };
  33637. /**
  33638. * Creates a polygon mesh.
  33639. * Please consider using the same method from the MeshBuilder class instead.
  33640. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33641. * 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.
  33642. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33643. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33644. * Remember you can only change the shape positions, not their number when updating a polygon.
  33645. */
  33646. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33647. var options = {
  33648. shape: shape,
  33649. holes: holes,
  33650. updatable: updatable,
  33651. sideOrientation: sideOrientation
  33652. };
  33653. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33654. };
  33655. /**
  33656. * Creates an extruded polygon mesh, with depth in the Y direction.
  33657. * Please consider using the same method from the MeshBuilder class instead.
  33658. */
  33659. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33660. var options = {
  33661. shape: shape,
  33662. holes: holes,
  33663. depth: depth,
  33664. updatable: updatable,
  33665. sideOrientation: sideOrientation
  33666. };
  33667. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33668. };
  33669. /**
  33670. * Creates an extruded shape mesh.
  33671. * 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.
  33672. * Please consider using the same method from the MeshBuilder class instead.
  33673. *
  33674. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33675. * 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
  33676. * extruded along the Z axis.
  33677. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33678. * 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.
  33679. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33680. * 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
  33681. * 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
  33682. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33684. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33686. */
  33687. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33688. if (scene === void 0) { scene = null; }
  33689. var options = {
  33690. shape: shape,
  33691. path: path,
  33692. scale: scale,
  33693. rotation: rotation,
  33694. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33695. sideOrientation: sideOrientation,
  33696. instance: instance,
  33697. updatable: updatable
  33698. };
  33699. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33700. };
  33701. /**
  33702. * Creates an custom extruded shape mesh.
  33703. * 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.
  33704. * Please consider using the same method from the MeshBuilder class instead.
  33705. *
  33706. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33707. * 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
  33708. * extruded along the Z axis.
  33709. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33710. * 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
  33711. * and the distance of this point from the begining of the path :
  33712. * ```javascript
  33713. * var rotationFunction = function(i, distance) {
  33714. * // do things
  33715. * return rotationValue; }
  33716. * ```
  33717. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33718. * 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
  33719. * and the distance of this point from the begining of the path :
  33720. * ```javascript
  33721. * var scaleFunction = function(i, distance) {
  33722. * // do things
  33723. * return scaleValue;}
  33724. * ```
  33725. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33726. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33727. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33728. * 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
  33729. * 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
  33730. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33732. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33734. */
  33735. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33736. var options = {
  33737. shape: shape,
  33738. path: path,
  33739. scaleFunction: scaleFunction,
  33740. rotationFunction: rotationFunction,
  33741. ribbonCloseArray: ribbonCloseArray,
  33742. ribbonClosePath: ribbonClosePath,
  33743. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33744. sideOrientation: sideOrientation,
  33745. instance: instance,
  33746. updatable: updatable
  33747. };
  33748. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33749. };
  33750. /**
  33751. * Creates lathe mesh.
  33752. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33753. * Please consider using the same method from the MeshBuilder class instead.
  33754. * 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
  33755. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33756. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33757. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33758. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33759. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33761. */
  33762. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33763. var options = {
  33764. shape: shape,
  33765. radius: radius,
  33766. tessellation: tessellation,
  33767. sideOrientation: sideOrientation,
  33768. updatable: updatable
  33769. };
  33770. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33771. };
  33772. /**
  33773. * Creates a plane mesh.
  33774. * Please consider using the same method from the MeshBuilder class instead.
  33775. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33777. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33778. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33779. */
  33780. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33781. var options = {
  33782. size: size,
  33783. width: size,
  33784. height: size,
  33785. sideOrientation: sideOrientation,
  33786. updatable: updatable
  33787. };
  33788. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33789. };
  33790. /**
  33791. * Creates a ground mesh.
  33792. * Please consider using the same method from the MeshBuilder class instead.
  33793. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33794. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33795. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33796. */
  33797. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33798. var options = {
  33799. width: width,
  33800. height: height,
  33801. subdivisions: subdivisions,
  33802. updatable: updatable
  33803. };
  33804. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33805. };
  33806. /**
  33807. * Creates a tiled ground mesh.
  33808. * Please consider using the same method from the MeshBuilder class instead.
  33809. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33810. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33811. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33812. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33813. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33814. * numbers of subdivisions on the ground width and height of each tile.
  33815. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33816. */
  33817. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33818. var options = {
  33819. xmin: xmin,
  33820. zmin: zmin,
  33821. xmax: xmax,
  33822. zmax: zmax,
  33823. subdivisions: subdivisions,
  33824. precision: precision,
  33825. updatable: updatable
  33826. };
  33827. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33828. };
  33829. /**
  33830. * Creates a ground mesh from a height map.
  33831. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33832. * Please consider using the same method from the MeshBuilder class instead.
  33833. * The parameter `url` sets the URL of the height map image resource.
  33834. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33835. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33836. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33837. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33838. * 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).
  33839. * This function is passed the newly built mesh :
  33840. * ```javascript
  33841. * function(mesh) { // do things
  33842. * return; }
  33843. * ```
  33844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33845. */
  33846. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33847. var options = {
  33848. width: width,
  33849. height: height,
  33850. subdivisions: subdivisions,
  33851. minHeight: minHeight,
  33852. maxHeight: maxHeight,
  33853. updatable: updatable,
  33854. onReady: onReady
  33855. };
  33856. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33857. };
  33858. /**
  33859. * Creates a tube mesh.
  33860. * 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.
  33861. * Please consider using the same method from the MeshBuilder class instead.
  33862. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33863. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33864. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33865. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33866. * 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.
  33867. * It must return a radius value (positive float) :
  33868. * ```javascript
  33869. * var radiusFunction = function(i, distance) {
  33870. * // do things
  33871. * return radius; }
  33872. * ```
  33873. * 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
  33874. * 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
  33875. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33876. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33877. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33878. */
  33879. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33880. var options = {
  33881. path: path,
  33882. radius: radius,
  33883. tessellation: tessellation,
  33884. radiusFunction: radiusFunction,
  33885. arc: 1,
  33886. cap: cap,
  33887. updatable: updatable,
  33888. sideOrientation: sideOrientation,
  33889. instance: instance
  33890. };
  33891. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33892. };
  33893. /**
  33894. * Creates a polyhedron mesh.
  33895. * Please consider using the same method from the MeshBuilder class instead.
  33896. * 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
  33897. * to choose the wanted type.
  33898. * The parameter `size` (positive float, default 1) sets the polygon size.
  33899. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33900. * 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`.
  33901. * 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
  33902. * 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)`).
  33903. * 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
  33904. * 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.
  33905. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33906. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33907. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33908. */
  33909. Mesh.CreatePolyhedron = function (name, options, scene) {
  33910. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33911. };
  33912. /**
  33913. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33914. * Please consider using the same method from the MeshBuilder class instead.
  33915. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33916. * 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`).
  33917. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33918. * 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.
  33919. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33920. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33921. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33922. */
  33923. Mesh.CreateIcoSphere = function (name, options, scene) {
  33924. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33925. };
  33926. /**
  33927. * Creates a decal mesh.
  33928. * Please consider using the same method from the MeshBuilder class instead.
  33929. * 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.
  33930. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33931. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33932. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33933. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33934. */
  33935. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33936. var options = {
  33937. position: position,
  33938. normal: normal,
  33939. size: size,
  33940. angle: angle
  33941. };
  33942. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33943. };
  33944. // Skeletons
  33945. /**
  33946. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33947. */
  33948. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33949. if (!this._sourcePositions) {
  33950. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33951. if (!source) {
  33952. return this._sourcePositions;
  33953. }
  33954. this._sourcePositions = new Float32Array(source);
  33955. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33956. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33957. }
  33958. }
  33959. return this._sourcePositions;
  33960. };
  33961. /**
  33962. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33963. */
  33964. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33965. if (!this._sourceNormals) {
  33966. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33967. if (!source) {
  33968. return this._sourceNormals;
  33969. }
  33970. this._sourceNormals = new Float32Array(source);
  33971. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33972. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33973. }
  33974. }
  33975. return this._sourceNormals;
  33976. };
  33977. /**
  33978. * Updates the vertex buffer by applying transformation from the bones.
  33979. * Returns the Mesh.
  33980. *
  33981. * @param {skeleton} skeleton to apply
  33982. */
  33983. Mesh.prototype.applySkeleton = function (skeleton) {
  33984. if (!this.geometry) {
  33985. return this;
  33986. }
  33987. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33988. return this;
  33989. }
  33990. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33991. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33992. return this;
  33993. }
  33994. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33995. return this;
  33996. }
  33997. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33998. return this;
  33999. }
  34000. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34001. return this;
  34002. }
  34003. if (!this._sourcePositions) {
  34004. var submeshes = this.subMeshes.slice();
  34005. this.setPositionsForCPUSkinning();
  34006. this.subMeshes = submeshes;
  34007. }
  34008. if (!this._sourceNormals) {
  34009. this.setNormalsForCPUSkinning();
  34010. }
  34011. // positionsData checks for not being Float32Array will only pass at most once
  34012. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34013. if (!positionsData) {
  34014. return this;
  34015. }
  34016. if (!(positionsData instanceof Float32Array)) {
  34017. positionsData = new Float32Array(positionsData);
  34018. }
  34019. // normalsData checks for not being Float32Array will only pass at most once
  34020. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34021. if (!normalsData) {
  34022. return this;
  34023. }
  34024. if (!(normalsData instanceof Float32Array)) {
  34025. normalsData = new Float32Array(normalsData);
  34026. }
  34027. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34028. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34029. if (!matricesWeightsData || !matricesIndicesData) {
  34030. return this;
  34031. }
  34032. var needExtras = this.numBoneInfluencers > 4;
  34033. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34034. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34035. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34036. var tempVector3 = BABYLON.Vector3.Zero();
  34037. var finalMatrix = new BABYLON.Matrix();
  34038. var tempMatrix = new BABYLON.Matrix();
  34039. var matWeightIdx = 0;
  34040. var inf;
  34041. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34042. var weight;
  34043. for (inf = 0; inf < 4; inf++) {
  34044. weight = matricesWeightsData[matWeightIdx + inf];
  34045. if (weight > 0) {
  34046. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34047. finalMatrix.addToSelf(tempMatrix);
  34048. }
  34049. else
  34050. break;
  34051. }
  34052. if (needExtras) {
  34053. for (inf = 0; inf < 4; inf++) {
  34054. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34055. if (weight > 0) {
  34056. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34057. finalMatrix.addToSelf(tempMatrix);
  34058. }
  34059. else
  34060. break;
  34061. }
  34062. }
  34063. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34064. tempVector3.toArray(positionsData, index);
  34065. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34066. tempVector3.toArray(normalsData, index);
  34067. finalMatrix.reset();
  34068. }
  34069. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34070. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34071. return this;
  34072. };
  34073. // Tools
  34074. /**
  34075. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34076. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34077. */
  34078. Mesh.MinMax = function (meshes) {
  34079. var minVector = null;
  34080. var maxVector = null;
  34081. meshes.forEach(function (mesh, index, array) {
  34082. var boundingInfo = mesh.getBoundingInfo();
  34083. var boundingBox = boundingInfo.boundingBox;
  34084. if (!minVector || !maxVector) {
  34085. minVector = boundingBox.minimumWorld;
  34086. maxVector = boundingBox.maximumWorld;
  34087. }
  34088. else {
  34089. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34090. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34091. }
  34092. });
  34093. if (!minVector || !maxVector) {
  34094. return {
  34095. min: BABYLON.Vector3.Zero(),
  34096. max: BABYLON.Vector3.Zero()
  34097. };
  34098. }
  34099. return {
  34100. min: minVector,
  34101. max: maxVector
  34102. };
  34103. };
  34104. /**
  34105. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34106. */
  34107. Mesh.Center = function (meshesOrMinMaxVector) {
  34108. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34109. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34110. };
  34111. /**
  34112. * Merge the array of meshes into a single mesh for performance reasons.
  34113. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34114. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34115. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34116. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34117. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34118. */
  34119. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34120. if (disposeSource === void 0) { disposeSource = true; }
  34121. var index;
  34122. if (!allow32BitsIndices) {
  34123. var totalVertices = 0;
  34124. // Counting vertices
  34125. for (index = 0; index < meshes.length; index++) {
  34126. if (meshes[index]) {
  34127. totalVertices += meshes[index].getTotalVertices();
  34128. if (totalVertices > 65536) {
  34129. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34130. return null;
  34131. }
  34132. }
  34133. }
  34134. }
  34135. // Merge
  34136. var vertexData = null;
  34137. var otherVertexData;
  34138. var indiceArray = new Array();
  34139. var source = null;
  34140. for (index = 0; index < meshes.length; index++) {
  34141. if (meshes[index]) {
  34142. meshes[index].computeWorldMatrix(true);
  34143. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34144. otherVertexData.transform(meshes[index].getWorldMatrix());
  34145. if (vertexData) {
  34146. vertexData.merge(otherVertexData);
  34147. }
  34148. else {
  34149. vertexData = otherVertexData;
  34150. source = meshes[index];
  34151. }
  34152. if (subdivideWithSubMeshes) {
  34153. indiceArray.push(meshes[index].getTotalIndices());
  34154. }
  34155. }
  34156. }
  34157. source = source;
  34158. if (!meshSubclass) {
  34159. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34160. }
  34161. vertexData.applyToMesh(meshSubclass);
  34162. // Setting properties
  34163. meshSubclass.material = source.material;
  34164. meshSubclass.checkCollisions = source.checkCollisions;
  34165. // Cleaning
  34166. if (disposeSource) {
  34167. for (index = 0; index < meshes.length; index++) {
  34168. if (meshes[index]) {
  34169. meshes[index].dispose();
  34170. }
  34171. }
  34172. }
  34173. // Subdivide
  34174. if (subdivideWithSubMeshes) {
  34175. //-- Suppresions du submesh global
  34176. meshSubclass.releaseSubMeshes();
  34177. index = 0;
  34178. var offset = 0;
  34179. //-- aplique la subdivision en fonction du tableau d'indices
  34180. while (index < indiceArray.length) {
  34181. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34182. offset += indiceArray[index];
  34183. index++;
  34184. }
  34185. }
  34186. return meshSubclass;
  34187. };
  34188. // Consts
  34189. Mesh._FRONTSIDE = 0;
  34190. Mesh._BACKSIDE = 1;
  34191. Mesh._DOUBLESIDE = 2;
  34192. Mesh._DEFAULTSIDE = 0;
  34193. Mesh._NO_CAP = 0;
  34194. Mesh._CAP_START = 1;
  34195. Mesh._CAP_END = 2;
  34196. Mesh._CAP_ALL = 3;
  34197. return Mesh;
  34198. }(BABYLON.AbstractMesh));
  34199. BABYLON.Mesh = Mesh;
  34200. })(BABYLON || (BABYLON = {}));
  34201. //# sourceMappingURL=babylon.mesh.js.map
  34202. var BABYLON;
  34203. (function (BABYLON) {
  34204. var BaseSubMesh = /** @class */ (function () {
  34205. function BaseSubMesh() {
  34206. }
  34207. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34208. get: function () {
  34209. return this._materialEffect;
  34210. },
  34211. enumerable: true,
  34212. configurable: true
  34213. });
  34214. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34215. if (defines === void 0) { defines = null; }
  34216. if (this._materialEffect === effect) {
  34217. if (!effect) {
  34218. this._materialDefines = null;
  34219. }
  34220. return;
  34221. }
  34222. this._materialDefines = defines;
  34223. this._materialEffect = effect;
  34224. };
  34225. return BaseSubMesh;
  34226. }());
  34227. BABYLON.BaseSubMesh = BaseSubMesh;
  34228. var SubMesh = /** @class */ (function (_super) {
  34229. __extends(SubMesh, _super);
  34230. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34231. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34232. var _this = _super.call(this) || this;
  34233. _this.materialIndex = materialIndex;
  34234. _this.verticesStart = verticesStart;
  34235. _this.verticesCount = verticesCount;
  34236. _this.indexStart = indexStart;
  34237. _this.indexCount = indexCount;
  34238. _this._renderId = 0;
  34239. _this._mesh = mesh;
  34240. _this._renderingMesh = renderingMesh || mesh;
  34241. mesh.subMeshes.push(_this);
  34242. _this._trianglePlanes = [];
  34243. _this._id = mesh.subMeshes.length - 1;
  34244. if (createBoundingBox) {
  34245. _this.refreshBoundingInfo();
  34246. mesh.computeWorldMatrix(true);
  34247. }
  34248. return _this;
  34249. }
  34250. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34251. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34252. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34253. };
  34254. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34255. get: function () {
  34256. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34257. },
  34258. enumerable: true,
  34259. configurable: true
  34260. });
  34261. /**
  34262. * Returns the submesh BoudingInfo object.
  34263. */
  34264. SubMesh.prototype.getBoundingInfo = function () {
  34265. if (this.IsGlobal) {
  34266. return this._mesh.getBoundingInfo();
  34267. }
  34268. return this._boundingInfo;
  34269. };
  34270. /**
  34271. * Sets the submesh BoundingInfo.
  34272. * Return the SubMesh.
  34273. */
  34274. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34275. this._boundingInfo = boundingInfo;
  34276. return this;
  34277. };
  34278. /**
  34279. * Returns the mesh of the current submesh.
  34280. */
  34281. SubMesh.prototype.getMesh = function () {
  34282. return this._mesh;
  34283. };
  34284. /**
  34285. * Returns the rendering mesh of the submesh.
  34286. */
  34287. SubMesh.prototype.getRenderingMesh = function () {
  34288. return this._renderingMesh;
  34289. };
  34290. /**
  34291. * Returns the submesh material.
  34292. */
  34293. SubMesh.prototype.getMaterial = function () {
  34294. var rootMaterial = this._renderingMesh.material;
  34295. if (rootMaterial === null || rootMaterial === undefined) {
  34296. return this._mesh.getScene().defaultMaterial;
  34297. }
  34298. else if (rootMaterial.getSubMaterial) {
  34299. var multiMaterial = rootMaterial;
  34300. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34301. if (this._currentMaterial !== effectiveMaterial) {
  34302. this._currentMaterial = effectiveMaterial;
  34303. this._materialDefines = null;
  34304. }
  34305. return effectiveMaterial;
  34306. }
  34307. return rootMaterial;
  34308. };
  34309. // Methods
  34310. /**
  34311. * Sets a new updated BoundingInfo object to the submesh.
  34312. * Returns the SubMesh.
  34313. */
  34314. SubMesh.prototype.refreshBoundingInfo = function () {
  34315. this._lastColliderWorldVertices = null;
  34316. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34317. return this;
  34318. }
  34319. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34320. if (!data) {
  34321. this._boundingInfo = this._mesh.getBoundingInfo();
  34322. return this;
  34323. }
  34324. var indices = this._renderingMesh.getIndices();
  34325. var extend;
  34326. //is this the only submesh?
  34327. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34328. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34329. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34330. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34331. }
  34332. else {
  34333. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34334. }
  34335. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34336. return this;
  34337. };
  34338. SubMesh.prototype._checkCollision = function (collider) {
  34339. var boundingInfo = this.getBoundingInfo();
  34340. return boundingInfo._checkCollision(collider);
  34341. };
  34342. /**
  34343. * Updates the submesh BoundingInfo.
  34344. * Returns the Submesh.
  34345. */
  34346. SubMesh.prototype.updateBoundingInfo = function (world) {
  34347. var boundingInfo = this.getBoundingInfo();
  34348. if (!boundingInfo) {
  34349. this.refreshBoundingInfo();
  34350. boundingInfo = this.getBoundingInfo();
  34351. }
  34352. boundingInfo.update(world);
  34353. return this;
  34354. };
  34355. /**
  34356. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34357. * Boolean returned.
  34358. */
  34359. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34360. var boundingInfo = this.getBoundingInfo();
  34361. if (!boundingInfo) {
  34362. return false;
  34363. }
  34364. return boundingInfo.isInFrustum(frustumPlanes);
  34365. };
  34366. /**
  34367. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34368. * Boolean returned.
  34369. */
  34370. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34371. var boundingInfo = this.getBoundingInfo();
  34372. if (!boundingInfo) {
  34373. return false;
  34374. }
  34375. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34376. };
  34377. /**
  34378. * Renders the submesh.
  34379. * Returns it.
  34380. */
  34381. SubMesh.prototype.render = function (enableAlphaMode) {
  34382. this._renderingMesh.render(this, enableAlphaMode);
  34383. return this;
  34384. };
  34385. /**
  34386. * Returns a new Index Buffer.
  34387. * Type returned : WebGLBuffer.
  34388. */
  34389. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34390. if (!this._linesIndexBuffer) {
  34391. var linesIndices = [];
  34392. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34393. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34394. }
  34395. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34396. this.linesIndexCount = linesIndices.length;
  34397. }
  34398. return this._linesIndexBuffer;
  34399. };
  34400. /**
  34401. * True is the passed Ray intersects the submesh bounding box.
  34402. * Boolean returned.
  34403. */
  34404. SubMesh.prototype.canIntersects = function (ray) {
  34405. var boundingInfo = this.getBoundingInfo();
  34406. if (!boundingInfo) {
  34407. return false;
  34408. }
  34409. return ray.intersectsBox(boundingInfo.boundingBox);
  34410. };
  34411. /**
  34412. * Returns an object IntersectionInfo.
  34413. */
  34414. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34415. var intersectInfo = null;
  34416. var material = this.getMaterial();
  34417. if (!material) {
  34418. return null;
  34419. }
  34420. switch (material.fillMode) {
  34421. case BABYLON.Material.PointListDrawMode:
  34422. case BABYLON.Material.LineListDrawMode:
  34423. case BABYLON.Material.LineLoopDrawMode:
  34424. case BABYLON.Material.LineStripDrawMode:
  34425. case BABYLON.Material.TriangleFanDrawMode:
  34426. case BABYLON.Material.TriangleStripDrawMode:
  34427. return null;
  34428. }
  34429. // LineMesh first as it's also a Mesh...
  34430. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34431. var lineMesh = this._mesh;
  34432. // Line test
  34433. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34434. var p0 = positions[indices[index]];
  34435. var p1 = positions[indices[index + 1]];
  34436. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34437. if (length < 0) {
  34438. continue;
  34439. }
  34440. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34441. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34442. if (fastCheck) {
  34443. break;
  34444. }
  34445. }
  34446. }
  34447. }
  34448. else {
  34449. // Triangles test
  34450. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34451. var p0 = positions[indices[index]];
  34452. var p1 = positions[indices[index + 1]];
  34453. var p2 = positions[indices[index + 2]];
  34454. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34455. if (currentIntersectInfo) {
  34456. if (currentIntersectInfo.distance < 0) {
  34457. continue;
  34458. }
  34459. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34460. intersectInfo = currentIntersectInfo;
  34461. intersectInfo.faceId = index / 3;
  34462. if (fastCheck) {
  34463. break;
  34464. }
  34465. }
  34466. }
  34467. }
  34468. }
  34469. return intersectInfo;
  34470. };
  34471. SubMesh.prototype._rebuild = function () {
  34472. if (this._linesIndexBuffer) {
  34473. this._linesIndexBuffer = null;
  34474. }
  34475. };
  34476. // Clone
  34477. /**
  34478. * Creates a new Submesh from the passed Mesh.
  34479. */
  34480. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34481. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34482. if (!this.IsGlobal) {
  34483. var boundingInfo = this.getBoundingInfo();
  34484. if (!boundingInfo) {
  34485. return result;
  34486. }
  34487. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34488. }
  34489. return result;
  34490. };
  34491. // Dispose
  34492. /**
  34493. * Disposes the Submesh.
  34494. * Returns nothing.
  34495. */
  34496. SubMesh.prototype.dispose = function () {
  34497. if (this._linesIndexBuffer) {
  34498. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34499. this._linesIndexBuffer = null;
  34500. }
  34501. // Remove from mesh
  34502. var index = this._mesh.subMeshes.indexOf(this);
  34503. this._mesh.subMeshes.splice(index, 1);
  34504. };
  34505. // Statics
  34506. /**
  34507. * Creates a new Submesh from the passed parameters :
  34508. * - materialIndex (integer) : the index of the main mesh material.
  34509. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34510. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34511. * - mesh (Mesh) : the main mesh to create the submesh from.
  34512. * - renderingMesh (optional Mesh) : rendering mesh.
  34513. */
  34514. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34515. var minVertexIndex = Number.MAX_VALUE;
  34516. var maxVertexIndex = -Number.MAX_VALUE;
  34517. renderingMesh = (renderingMesh || mesh);
  34518. var indices = renderingMesh.getIndices();
  34519. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34520. var vertexIndex = indices[index];
  34521. if (vertexIndex < minVertexIndex)
  34522. minVertexIndex = vertexIndex;
  34523. if (vertexIndex > maxVertexIndex)
  34524. maxVertexIndex = vertexIndex;
  34525. }
  34526. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34527. };
  34528. return SubMesh;
  34529. }(BaseSubMesh));
  34530. BABYLON.SubMesh = SubMesh;
  34531. })(BABYLON || (BABYLON = {}));
  34532. //# sourceMappingURL=babylon.subMesh.js.map
  34533. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34534. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34535. s = arguments[i];
  34536. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34537. t[p] = s[p];
  34538. }
  34539. return t;
  34540. };
  34541. var BABYLON;
  34542. (function (BABYLON) {
  34543. /**
  34544. * Manages the defines for the Material
  34545. */
  34546. var MaterialDefines = /** @class */ (function () {
  34547. function MaterialDefines() {
  34548. this._isDirty = true;
  34549. /** @hidden */
  34550. this._areLightsDirty = true;
  34551. /** @hidden */
  34552. this._areAttributesDirty = true;
  34553. /** @hidden */
  34554. this._areTexturesDirty = true;
  34555. /** @hidden */
  34556. this._areFresnelDirty = true;
  34557. /** @hidden */
  34558. this._areMiscDirty = true;
  34559. /** @hidden */
  34560. this._areImageProcessingDirty = true;
  34561. /** @hidden */
  34562. this._normals = false;
  34563. /** @hidden */
  34564. this._uvs = false;
  34565. /** @hidden */
  34566. this._needNormals = false;
  34567. /** @hidden */
  34568. this._needUVs = false;
  34569. }
  34570. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34571. /**
  34572. * Specifies if the material needs to be re-calculated
  34573. */
  34574. get: function () {
  34575. return this._isDirty;
  34576. },
  34577. enumerable: true,
  34578. configurable: true
  34579. });
  34580. /**
  34581. * Marks the material to indicate that it has been re-calculated
  34582. */
  34583. MaterialDefines.prototype.markAsProcessed = function () {
  34584. this._isDirty = false;
  34585. this._areAttributesDirty = false;
  34586. this._areTexturesDirty = false;
  34587. this._areFresnelDirty = false;
  34588. this._areLightsDirty = false;
  34589. this._areMiscDirty = false;
  34590. this._areImageProcessingDirty = false;
  34591. };
  34592. /**
  34593. * Marks the material to indicate that it needs to be re-calculated
  34594. */
  34595. MaterialDefines.prototype.markAsUnprocessed = function () {
  34596. this._isDirty = true;
  34597. };
  34598. /**
  34599. * Marks the material to indicate all of its defines need to be re-calculated
  34600. */
  34601. MaterialDefines.prototype.markAllAsDirty = function () {
  34602. this._areTexturesDirty = true;
  34603. this._areAttributesDirty = true;
  34604. this._areLightsDirty = true;
  34605. this._areFresnelDirty = true;
  34606. this._areMiscDirty = true;
  34607. this._areImageProcessingDirty = true;
  34608. this._isDirty = true;
  34609. };
  34610. /**
  34611. * Marks the material to indicate that image processing needs to be re-calculated
  34612. */
  34613. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34614. this._areImageProcessingDirty = true;
  34615. this._isDirty = true;
  34616. };
  34617. /**
  34618. * Marks the material to indicate the lights need to be re-calculated
  34619. */
  34620. MaterialDefines.prototype.markAsLightDirty = function () {
  34621. this._areLightsDirty = true;
  34622. this._isDirty = true;
  34623. };
  34624. /**
  34625. * Marks the attribute state as changed
  34626. */
  34627. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34628. this._areAttributesDirty = true;
  34629. this._isDirty = true;
  34630. };
  34631. /**
  34632. * Marks the texture state as changed
  34633. */
  34634. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34635. this._areTexturesDirty = true;
  34636. this._isDirty = true;
  34637. };
  34638. /**
  34639. * Marks the fresnel state as changed
  34640. */
  34641. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34642. this._areFresnelDirty = true;
  34643. this._isDirty = true;
  34644. };
  34645. /**
  34646. * Marks the misc state as changed
  34647. */
  34648. MaterialDefines.prototype.markAsMiscDirty = function () {
  34649. this._areMiscDirty = true;
  34650. this._isDirty = true;
  34651. };
  34652. /**
  34653. * Rebuilds the material defines
  34654. */
  34655. MaterialDefines.prototype.rebuild = function () {
  34656. if (this._keys) {
  34657. delete this._keys;
  34658. }
  34659. this._keys = [];
  34660. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34661. var key = _a[_i];
  34662. if (key[0] === "_") {
  34663. continue;
  34664. }
  34665. this._keys.push(key);
  34666. }
  34667. };
  34668. /**
  34669. * Specifies if two material defines are equal
  34670. * @param other - A material define instance to compare to
  34671. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34672. */
  34673. MaterialDefines.prototype.isEqual = function (other) {
  34674. if (this._keys.length !== other._keys.length) {
  34675. return false;
  34676. }
  34677. for (var index = 0; index < this._keys.length; index++) {
  34678. var prop = this._keys[index];
  34679. if (this[prop] !== other[prop]) {
  34680. return false;
  34681. }
  34682. }
  34683. return true;
  34684. };
  34685. /**
  34686. * Clones this instance's defines to another instance
  34687. * @param other - material defines to clone values to
  34688. */
  34689. MaterialDefines.prototype.cloneTo = function (other) {
  34690. if (this._keys.length !== other._keys.length) {
  34691. other._keys = this._keys.slice(0);
  34692. }
  34693. for (var index = 0; index < this._keys.length; index++) {
  34694. var prop = this._keys[index];
  34695. other[prop] = this[prop];
  34696. }
  34697. };
  34698. /**
  34699. * Resets the material define values
  34700. */
  34701. MaterialDefines.prototype.reset = function () {
  34702. for (var index = 0; index < this._keys.length; index++) {
  34703. var prop = this._keys[index];
  34704. var type = typeof this[prop];
  34705. switch (type) {
  34706. case "number":
  34707. this[prop] = 0;
  34708. break;
  34709. case "string":
  34710. this[prop] = "";
  34711. break;
  34712. default:
  34713. this[prop] = false;
  34714. break;
  34715. }
  34716. }
  34717. };
  34718. /**
  34719. * Converts the material define values to a string
  34720. * @returns - String of material define information
  34721. */
  34722. MaterialDefines.prototype.toString = function () {
  34723. var result = "";
  34724. for (var index = 0; index < this._keys.length; index++) {
  34725. var prop = this._keys[index];
  34726. var value = this[prop];
  34727. var type = typeof value;
  34728. switch (type) {
  34729. case "number":
  34730. case "string":
  34731. result += "#define " + prop + " " + value + "\n";
  34732. break;
  34733. default:
  34734. if (value) {
  34735. result += "#define " + prop + "\n";
  34736. }
  34737. break;
  34738. }
  34739. }
  34740. return result;
  34741. };
  34742. return MaterialDefines;
  34743. }());
  34744. BABYLON.MaterialDefines = MaterialDefines;
  34745. /**
  34746. * Base class for the main features of a material in Babylon.js
  34747. */
  34748. var Material = /** @class */ (function () {
  34749. /**
  34750. * Creates a material instance
  34751. * @param name defines the name of the material
  34752. * @param scene defines the scene to reference
  34753. * @param doNotAdd specifies if the material should be added to the scene
  34754. */
  34755. function Material(name, scene, doNotAdd) {
  34756. /**
  34757. * Specifies if the ready state should be checked on each call
  34758. */
  34759. this.checkReadyOnEveryCall = false;
  34760. /**
  34761. * Specifies if the ready state should be checked once
  34762. */
  34763. this.checkReadyOnlyOnce = false;
  34764. /**
  34765. * The state of the material
  34766. */
  34767. this.state = "";
  34768. /**
  34769. * The alpha value of the material
  34770. */
  34771. this._alpha = 1.0;
  34772. /**
  34773. * Specifies if back face culling is enabled
  34774. */
  34775. this._backFaceCulling = true;
  34776. /**
  34777. * Specifies if the material should be serialized
  34778. */
  34779. this.doNotSerialize = false;
  34780. /**
  34781. * Specifies if the effect should be stored on sub meshes
  34782. */
  34783. this.storeEffectOnSubMeshes = false;
  34784. /**
  34785. * An event triggered when the material is disposed
  34786. */
  34787. this.onDisposeObservable = new BABYLON.Observable();
  34788. /**
  34789. * An event triggered when the material is bound
  34790. */
  34791. this.onBindObservable = new BABYLON.Observable();
  34792. /**
  34793. * An event triggered when the material is unbound
  34794. */
  34795. this.onUnBindObservable = new BABYLON.Observable();
  34796. /**
  34797. * Stores the value of the alpha mode
  34798. */
  34799. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34800. /**
  34801. * Stores the state of the need depth pre-pass value
  34802. */
  34803. this._needDepthPrePass = false;
  34804. /**
  34805. * Specifies if depth writing should be disabled
  34806. */
  34807. this.disableDepthWrite = false;
  34808. /**
  34809. * Specifies if depth writing should be forced
  34810. */
  34811. this.forceDepthWrite = false;
  34812. /**
  34813. * Specifies if there should be a separate pass for culling
  34814. */
  34815. this.separateCullingPass = false;
  34816. /**
  34817. * Stores the state specifing if fog should be enabled
  34818. */
  34819. this._fogEnabled = true;
  34820. /**
  34821. * Stores the size of points
  34822. */
  34823. this.pointSize = 1.0;
  34824. /**
  34825. * Stores the z offset value
  34826. */
  34827. this.zOffset = 0;
  34828. /**
  34829. * Specifies if the material was previously ready
  34830. */
  34831. this._wasPreviouslyReady = false;
  34832. /**
  34833. * Stores the fill mode state
  34834. */
  34835. this._fillMode = Material.TriangleFillMode;
  34836. this.name = name;
  34837. this.id = name || BABYLON.Tools.RandomId();
  34838. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34839. this.uniqueId = this._scene.getUniqueId();
  34840. if (this._scene.useRightHandedSystem) {
  34841. this.sideOrientation = Material.ClockWiseSideOrientation;
  34842. }
  34843. else {
  34844. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34845. }
  34846. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34847. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34848. if (!doNotAdd) {
  34849. this._scene.materials.push(this);
  34850. }
  34851. }
  34852. Object.defineProperty(Material, "TriangleFillMode", {
  34853. /**
  34854. * Returns the triangle fill mode
  34855. */
  34856. get: function () {
  34857. return Material._TriangleFillMode;
  34858. },
  34859. enumerable: true,
  34860. configurable: true
  34861. });
  34862. Object.defineProperty(Material, "WireFrameFillMode", {
  34863. /**
  34864. * Returns the wireframe mode
  34865. */
  34866. get: function () {
  34867. return Material._WireFrameFillMode;
  34868. },
  34869. enumerable: true,
  34870. configurable: true
  34871. });
  34872. Object.defineProperty(Material, "PointFillMode", {
  34873. /**
  34874. * Returns the point fill mode
  34875. */
  34876. get: function () {
  34877. return Material._PointFillMode;
  34878. },
  34879. enumerable: true,
  34880. configurable: true
  34881. });
  34882. Object.defineProperty(Material, "PointListDrawMode", {
  34883. /**
  34884. * Returns the point list draw mode
  34885. */
  34886. get: function () {
  34887. return Material._PointListDrawMode;
  34888. },
  34889. enumerable: true,
  34890. configurable: true
  34891. });
  34892. Object.defineProperty(Material, "LineListDrawMode", {
  34893. /**
  34894. * Returns the line list draw mode
  34895. */
  34896. get: function () {
  34897. return Material._LineListDrawMode;
  34898. },
  34899. enumerable: true,
  34900. configurable: true
  34901. });
  34902. Object.defineProperty(Material, "LineLoopDrawMode", {
  34903. /**
  34904. * Returns the line loop draw mode
  34905. */
  34906. get: function () {
  34907. return Material._LineLoopDrawMode;
  34908. },
  34909. enumerable: true,
  34910. configurable: true
  34911. });
  34912. Object.defineProperty(Material, "LineStripDrawMode", {
  34913. /**
  34914. * Returns the line strip draw mode
  34915. */
  34916. get: function () {
  34917. return Material._LineStripDrawMode;
  34918. },
  34919. enumerable: true,
  34920. configurable: true
  34921. });
  34922. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34923. /**
  34924. * Returns the triangle strip draw mode
  34925. */
  34926. get: function () {
  34927. return Material._TriangleStripDrawMode;
  34928. },
  34929. enumerable: true,
  34930. configurable: true
  34931. });
  34932. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34933. /**
  34934. * Returns the triangle fan draw mode
  34935. */
  34936. get: function () {
  34937. return Material._TriangleFanDrawMode;
  34938. },
  34939. enumerable: true,
  34940. configurable: true
  34941. });
  34942. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34943. /**
  34944. * Returns the clock-wise side orientation
  34945. */
  34946. get: function () {
  34947. return Material._ClockWiseSideOrientation;
  34948. },
  34949. enumerable: true,
  34950. configurable: true
  34951. });
  34952. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34953. /**
  34954. * Returns the counter clock-wise side orientation
  34955. */
  34956. get: function () {
  34957. return Material._CounterClockWiseSideOrientation;
  34958. },
  34959. enumerable: true,
  34960. configurable: true
  34961. });
  34962. Object.defineProperty(Material, "TextureDirtyFlag", {
  34963. /**
  34964. * Returns the dirty texture flag value
  34965. */
  34966. get: function () {
  34967. return Material._TextureDirtyFlag;
  34968. },
  34969. enumerable: true,
  34970. configurable: true
  34971. });
  34972. Object.defineProperty(Material, "LightDirtyFlag", {
  34973. /**
  34974. * Returns the dirty light flag value
  34975. */
  34976. get: function () {
  34977. return Material._LightDirtyFlag;
  34978. },
  34979. enumerable: true,
  34980. configurable: true
  34981. });
  34982. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34983. /**
  34984. * Returns the dirty fresnel flag value
  34985. */
  34986. get: function () {
  34987. return Material._FresnelDirtyFlag;
  34988. },
  34989. enumerable: true,
  34990. configurable: true
  34991. });
  34992. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34993. /**
  34994. * Returns the dirty attributes flag value
  34995. */
  34996. get: function () {
  34997. return Material._AttributesDirtyFlag;
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. Object.defineProperty(Material, "MiscDirtyFlag", {
  35003. /**
  35004. * Returns the dirty misc flag value
  35005. */
  35006. get: function () {
  35007. return Material._MiscDirtyFlag;
  35008. },
  35009. enumerable: true,
  35010. configurable: true
  35011. });
  35012. Object.defineProperty(Material.prototype, "alpha", {
  35013. /**
  35014. * Gets the alpha value of the material
  35015. */
  35016. get: function () {
  35017. return this._alpha;
  35018. },
  35019. /**
  35020. * Sets the alpha value of the material
  35021. */
  35022. set: function (value) {
  35023. if (this._alpha === value) {
  35024. return;
  35025. }
  35026. this._alpha = value;
  35027. this.markAsDirty(Material.MiscDirtyFlag);
  35028. },
  35029. enumerable: true,
  35030. configurable: true
  35031. });
  35032. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35033. /**
  35034. * Gets the back-face culling state
  35035. */
  35036. get: function () {
  35037. return this._backFaceCulling;
  35038. },
  35039. /**
  35040. * Sets the back-face culling state
  35041. */
  35042. set: function (value) {
  35043. if (this._backFaceCulling === value) {
  35044. return;
  35045. }
  35046. this._backFaceCulling = value;
  35047. this.markAsDirty(Material.TextureDirtyFlag);
  35048. },
  35049. enumerable: true,
  35050. configurable: true
  35051. });
  35052. Object.defineProperty(Material.prototype, "onDispose", {
  35053. /**
  35054. * Called during a dispose event
  35055. */
  35056. set: function (callback) {
  35057. if (this._onDisposeObserver) {
  35058. this.onDisposeObservable.remove(this._onDisposeObserver);
  35059. }
  35060. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35061. },
  35062. enumerable: true,
  35063. configurable: true
  35064. });
  35065. Object.defineProperty(Material.prototype, "onBind", {
  35066. /**
  35067. * Called during a bind event
  35068. */
  35069. set: function (callback) {
  35070. if (this._onBindObserver) {
  35071. this.onBindObservable.remove(this._onBindObserver);
  35072. }
  35073. this._onBindObserver = this.onBindObservable.add(callback);
  35074. },
  35075. enumerable: true,
  35076. configurable: true
  35077. });
  35078. Object.defineProperty(Material.prototype, "alphaMode", {
  35079. /**
  35080. * Gets the value of the alpha mode
  35081. */
  35082. get: function () {
  35083. return this._alphaMode;
  35084. },
  35085. /**
  35086. * Sets the value of the alpha mode.
  35087. *
  35088. * | Value | Type | Description |
  35089. * | --- | --- | --- |
  35090. * | 0 | ALPHA_DISABLE | |
  35091. * | 1 | ALPHA_ADD | |
  35092. * | 2 | ALPHA_COMBINE | |
  35093. * | 3 | ALPHA_SUBTRACT | |
  35094. * | 4 | ALPHA_MULTIPLY | |
  35095. * | 5 | ALPHA_MAXIMIZED | |
  35096. * | 6 | ALPHA_ONEONE | |
  35097. * | 7 | ALPHA_PREMULTIPLIED | |
  35098. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35099. * | 9 | ALPHA_INTERPOLATE | |
  35100. * | 10 | ALPHA_SCREENMODE | |
  35101. *
  35102. */
  35103. set: function (value) {
  35104. if (this._alphaMode === value) {
  35105. return;
  35106. }
  35107. this._alphaMode = value;
  35108. this.markAsDirty(Material.TextureDirtyFlag);
  35109. },
  35110. enumerable: true,
  35111. configurable: true
  35112. });
  35113. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35114. /**
  35115. * Gets the depth pre-pass value
  35116. */
  35117. get: function () {
  35118. return this._needDepthPrePass;
  35119. },
  35120. /**
  35121. * Sets the need depth pre-pass value
  35122. */
  35123. set: function (value) {
  35124. if (this._needDepthPrePass === value) {
  35125. return;
  35126. }
  35127. this._needDepthPrePass = value;
  35128. if (this._needDepthPrePass) {
  35129. this.checkReadyOnEveryCall = true;
  35130. }
  35131. },
  35132. enumerable: true,
  35133. configurable: true
  35134. });
  35135. Object.defineProperty(Material.prototype, "fogEnabled", {
  35136. /**
  35137. * Gets the value of the fog enabled state
  35138. */
  35139. get: function () {
  35140. return this._fogEnabled;
  35141. },
  35142. /**
  35143. * Sets the state for enabling fog
  35144. */
  35145. set: function (value) {
  35146. if (this._fogEnabled === value) {
  35147. return;
  35148. }
  35149. this._fogEnabled = value;
  35150. this.markAsDirty(Material.MiscDirtyFlag);
  35151. },
  35152. enumerable: true,
  35153. configurable: true
  35154. });
  35155. Object.defineProperty(Material.prototype, "wireframe", {
  35156. /**
  35157. * Gets a value specifying if wireframe mode is enabled
  35158. */
  35159. get: function () {
  35160. switch (this._fillMode) {
  35161. case Material.WireFrameFillMode:
  35162. case Material.LineListDrawMode:
  35163. case Material.LineLoopDrawMode:
  35164. case Material.LineStripDrawMode:
  35165. return true;
  35166. }
  35167. return this._scene.forceWireframe;
  35168. },
  35169. /**
  35170. * Sets the state of wireframe mode
  35171. */
  35172. set: function (value) {
  35173. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35174. },
  35175. enumerable: true,
  35176. configurable: true
  35177. });
  35178. Object.defineProperty(Material.prototype, "pointsCloud", {
  35179. /**
  35180. * Gets the value specifying if point clouds are enabled
  35181. */
  35182. get: function () {
  35183. switch (this._fillMode) {
  35184. case Material.PointFillMode:
  35185. case Material.PointListDrawMode:
  35186. return true;
  35187. }
  35188. return this._scene.forcePointsCloud;
  35189. },
  35190. /**
  35191. * Sets the state of point cloud mode
  35192. */
  35193. set: function (value) {
  35194. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35195. },
  35196. enumerable: true,
  35197. configurable: true
  35198. });
  35199. Object.defineProperty(Material.prototype, "fillMode", {
  35200. /**
  35201. * Gets the material fill mode
  35202. */
  35203. get: function () {
  35204. return this._fillMode;
  35205. },
  35206. /**
  35207. * Sets the material fill mode
  35208. */
  35209. set: function (value) {
  35210. if (this._fillMode === value) {
  35211. return;
  35212. }
  35213. this._fillMode = value;
  35214. this.markAsDirty(Material.MiscDirtyFlag);
  35215. },
  35216. enumerable: true,
  35217. configurable: true
  35218. });
  35219. /**
  35220. * Returns a string representation of the current material
  35221. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35222. * @returns a string with material information
  35223. */
  35224. Material.prototype.toString = function (fullDetails) {
  35225. var ret = "Name: " + this.name;
  35226. if (fullDetails) {
  35227. }
  35228. return ret;
  35229. };
  35230. /**
  35231. * Gets the class name of the material
  35232. * @returns a string with the class name of the material
  35233. */
  35234. Material.prototype.getClassName = function () {
  35235. return "Material";
  35236. };
  35237. Object.defineProperty(Material.prototype, "isFrozen", {
  35238. /**
  35239. * Specifies if updates for the material been locked
  35240. */
  35241. get: function () {
  35242. return this.checkReadyOnlyOnce;
  35243. },
  35244. enumerable: true,
  35245. configurable: true
  35246. });
  35247. /**
  35248. * Locks updates for the material
  35249. */
  35250. Material.prototype.freeze = function () {
  35251. this.checkReadyOnlyOnce = true;
  35252. };
  35253. /**
  35254. * Unlocks updates for the material
  35255. */
  35256. Material.prototype.unfreeze = function () {
  35257. this.checkReadyOnlyOnce = false;
  35258. };
  35259. /**
  35260. * Specifies if the material is ready to be used
  35261. * @param mesh defines the mesh to check
  35262. * @param useInstances specifies if instances should be used
  35263. * @returns a boolean indicating if the material is ready to be used
  35264. */
  35265. Material.prototype.isReady = function (mesh, useInstances) {
  35266. return true;
  35267. };
  35268. /**
  35269. * Specifies that the submesh is ready to be used
  35270. * @param mesh defines the mesh to check
  35271. * @param subMesh defines which submesh to check
  35272. * @param useInstances specifies that instances should be used
  35273. * @returns a boolean indicating that the submesh is ready or not
  35274. */
  35275. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35276. return false;
  35277. };
  35278. /**
  35279. * Returns the material effect
  35280. * @returns the effect associated with the material
  35281. */
  35282. Material.prototype.getEffect = function () {
  35283. return this._effect;
  35284. };
  35285. /**
  35286. * Returns the current scene
  35287. * @returns a Scene
  35288. */
  35289. Material.prototype.getScene = function () {
  35290. return this._scene;
  35291. };
  35292. /**
  35293. * Specifies if the material will require alpha blending
  35294. * @returns a boolean specifying if alpha blending is needed
  35295. */
  35296. Material.prototype.needAlphaBlending = function () {
  35297. return (this.alpha < 1.0);
  35298. };
  35299. /**
  35300. * Specifies if the mesh will require alpha blending
  35301. * @param mesh defines the mesh to check
  35302. * @returns a boolean specifying if alpha blending is needed for the mesh
  35303. */
  35304. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35305. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35306. };
  35307. /**
  35308. * Specifies if this material should be rendered in alpha test mode
  35309. * @returns a boolean specifying if an alpha test is needed.
  35310. */
  35311. Material.prototype.needAlphaTesting = function () {
  35312. return false;
  35313. };
  35314. /**
  35315. * Gets the texture used for the alpha test
  35316. * @returns the texture to use for alpha testing
  35317. */
  35318. Material.prototype.getAlphaTestTexture = function () {
  35319. return null;
  35320. };
  35321. /**
  35322. * Marks the material to indicate that it needs to be re-calculated
  35323. */
  35324. Material.prototype.markDirty = function () {
  35325. this._wasPreviouslyReady = false;
  35326. };
  35327. /** @hidden */
  35328. Material.prototype._preBind = function (effect, overrideOrientation) {
  35329. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35330. var engine = this._scene.getEngine();
  35331. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35332. var reverse = orientation === Material.ClockWiseSideOrientation;
  35333. engine.enableEffect(effect ? effect : this._effect);
  35334. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35335. return reverse;
  35336. };
  35337. /**
  35338. * Binds the material to the mesh
  35339. * @param world defines the world transformation matrix
  35340. * @param mesh defines the mesh to bind the material to
  35341. */
  35342. Material.prototype.bind = function (world, mesh) {
  35343. };
  35344. /**
  35345. * Binds the submesh to the material
  35346. * @param world defines the world transformation matrix
  35347. * @param mesh defines the mesh containing the submesh
  35348. * @param subMesh defines the submesh to bind the material to
  35349. */
  35350. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35351. };
  35352. /**
  35353. * Binds the world matrix to the material
  35354. * @param world defines the world transformation matrix
  35355. */
  35356. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35357. };
  35358. /**
  35359. * Binds the scene's uniform buffer to the effect.
  35360. * @param effect defines the effect to bind to the scene uniform buffer
  35361. * @param sceneUbo defines the uniform buffer storing scene data
  35362. */
  35363. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35364. sceneUbo.bindToEffect(effect, "Scene");
  35365. };
  35366. /**
  35367. * Binds the view matrix to the effect
  35368. * @param effect defines the effect to bind the view matrix to
  35369. */
  35370. Material.prototype.bindView = function (effect) {
  35371. if (!this._useUBO) {
  35372. effect.setMatrix("view", this.getScene().getViewMatrix());
  35373. }
  35374. else {
  35375. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35376. }
  35377. };
  35378. /**
  35379. * Binds the view projection matrix to the effect
  35380. * @param effect defines the effect to bind the view projection matrix to
  35381. */
  35382. Material.prototype.bindViewProjection = function (effect) {
  35383. if (!this._useUBO) {
  35384. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35385. }
  35386. else {
  35387. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35388. }
  35389. };
  35390. /**
  35391. * Specifies if material alpha testing should be turned on for the mesh
  35392. * @param mesh defines the mesh to check
  35393. */
  35394. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35395. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35396. };
  35397. /**
  35398. * Processes to execute after binding the material to a mesh
  35399. * @param mesh defines the rendered mesh
  35400. */
  35401. Material.prototype._afterBind = function (mesh) {
  35402. this._scene._cachedMaterial = this;
  35403. if (mesh) {
  35404. this._scene._cachedVisibility = mesh.visibility;
  35405. }
  35406. else {
  35407. this._scene._cachedVisibility = 1;
  35408. }
  35409. if (mesh) {
  35410. this.onBindObservable.notifyObservers(mesh);
  35411. }
  35412. if (this.disableDepthWrite) {
  35413. var engine = this._scene.getEngine();
  35414. this._cachedDepthWriteState = engine.getDepthWrite();
  35415. engine.setDepthWrite(false);
  35416. }
  35417. };
  35418. /**
  35419. * Unbinds the material from the mesh
  35420. */
  35421. Material.prototype.unbind = function () {
  35422. this.onUnBindObservable.notifyObservers(this);
  35423. if (this.disableDepthWrite) {
  35424. var engine = this._scene.getEngine();
  35425. engine.setDepthWrite(this._cachedDepthWriteState);
  35426. }
  35427. };
  35428. /**
  35429. * Gets the active textures from the material
  35430. * @returns an array of textures
  35431. */
  35432. Material.prototype.getActiveTextures = function () {
  35433. return [];
  35434. };
  35435. /**
  35436. * Specifies if the material uses a texture
  35437. * @param texture defines the texture to check against the material
  35438. * @returns a boolean specifying if the material uses the texture
  35439. */
  35440. Material.prototype.hasTexture = function (texture) {
  35441. return false;
  35442. };
  35443. /**
  35444. * Makes a duplicate of the material, and gives it a new name
  35445. * @param name defines the new name for the duplicated material
  35446. * @returns the cloned material
  35447. */
  35448. Material.prototype.clone = function (name) {
  35449. return null;
  35450. };
  35451. /**
  35452. * Gets the meshes bound to the material
  35453. * @returns an array of meshes bound to the material
  35454. */
  35455. Material.prototype.getBindedMeshes = function () {
  35456. var result = new Array();
  35457. for (var index = 0; index < this._scene.meshes.length; index++) {
  35458. var mesh = this._scene.meshes[index];
  35459. if (mesh.material === this) {
  35460. result.push(mesh);
  35461. }
  35462. }
  35463. return result;
  35464. };
  35465. /**
  35466. * Force shader compilation
  35467. * @param mesh defines the mesh associated with this material
  35468. * @param onCompiled defines a function to execute once the material is compiled
  35469. * @param options defines the options to configure the compilation
  35470. */
  35471. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35472. var _this = this;
  35473. var localOptions = __assign({ clipPlane: false }, options);
  35474. var subMesh = new BABYLON.BaseSubMesh();
  35475. var scene = this.getScene();
  35476. var checkReady = function () {
  35477. if (!_this._scene || !_this._scene.getEngine()) {
  35478. return;
  35479. }
  35480. if (subMesh._materialDefines) {
  35481. subMesh._materialDefines._renderId = -1;
  35482. }
  35483. var clipPlaneState = scene.clipPlane;
  35484. if (localOptions.clipPlane) {
  35485. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35486. }
  35487. if (_this.storeEffectOnSubMeshes) {
  35488. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35489. if (onCompiled) {
  35490. onCompiled(_this);
  35491. }
  35492. }
  35493. else {
  35494. setTimeout(checkReady, 16);
  35495. }
  35496. }
  35497. else {
  35498. if (_this.isReady(mesh)) {
  35499. if (onCompiled) {
  35500. onCompiled(_this);
  35501. }
  35502. }
  35503. else {
  35504. setTimeout(checkReady, 16);
  35505. }
  35506. }
  35507. if (localOptions.clipPlane) {
  35508. scene.clipPlane = clipPlaneState;
  35509. }
  35510. };
  35511. checkReady();
  35512. };
  35513. /**
  35514. * Force shader compilation
  35515. * @param mesh defines the mesh that will use this material
  35516. * @param options defines additional options for compiling the shaders
  35517. * @returns a promise that resolves when the compilation completes
  35518. */
  35519. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35520. var _this = this;
  35521. return new Promise(function (resolve) {
  35522. _this.forceCompilation(mesh, function () {
  35523. resolve();
  35524. }, options);
  35525. });
  35526. };
  35527. /**
  35528. * Marks a define in the material to indicate that it needs to be re-computed
  35529. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35530. */
  35531. Material.prototype.markAsDirty = function (flag) {
  35532. if (flag & Material.TextureDirtyFlag) {
  35533. this._markAllSubMeshesAsTexturesDirty();
  35534. }
  35535. if (flag & Material.LightDirtyFlag) {
  35536. this._markAllSubMeshesAsLightsDirty();
  35537. }
  35538. if (flag & Material.FresnelDirtyFlag) {
  35539. this._markAllSubMeshesAsFresnelDirty();
  35540. }
  35541. if (flag & Material.AttributesDirtyFlag) {
  35542. this._markAllSubMeshesAsAttributesDirty();
  35543. }
  35544. if (flag & Material.MiscDirtyFlag) {
  35545. this._markAllSubMeshesAsMiscDirty();
  35546. }
  35547. this.getScene().resetCachedMaterial();
  35548. };
  35549. /**
  35550. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35551. * @param func defines a function which checks material defines against the submeshes
  35552. */
  35553. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35554. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35555. var mesh = _a[_i];
  35556. if (!mesh.subMeshes) {
  35557. continue;
  35558. }
  35559. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35560. var subMesh = _c[_b];
  35561. if (subMesh.getMaterial() !== this) {
  35562. continue;
  35563. }
  35564. if (!subMesh._materialDefines) {
  35565. continue;
  35566. }
  35567. func(subMesh._materialDefines);
  35568. }
  35569. }
  35570. };
  35571. /**
  35572. * Indicates that image processing needs to be re-calculated for all submeshes
  35573. */
  35574. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35575. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35576. };
  35577. /**
  35578. * Indicates that textures need to be re-calculated for all submeshes
  35579. */
  35580. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35581. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35582. };
  35583. /**
  35584. * Indicates that fresnel needs to be re-calculated for all submeshes
  35585. */
  35586. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35587. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35588. };
  35589. /**
  35590. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35591. */
  35592. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35593. this._markAllSubMeshesAsDirty(function (defines) {
  35594. defines.markAsFresnelDirty();
  35595. defines.markAsMiscDirty();
  35596. });
  35597. };
  35598. /**
  35599. * Indicates that lights need to be re-calculated for all submeshes
  35600. */
  35601. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35602. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35603. };
  35604. /**
  35605. * Indicates that attributes need to be re-calculated for all submeshes
  35606. */
  35607. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35608. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35609. };
  35610. /**
  35611. * Indicates that misc needs to be re-calculated for all submeshes
  35612. */
  35613. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35614. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35615. };
  35616. /**
  35617. * Indicates that textures and misc need to be re-calculated for all submeshes
  35618. */
  35619. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35620. this._markAllSubMeshesAsDirty(function (defines) {
  35621. defines.markAsTexturesDirty();
  35622. defines.markAsMiscDirty();
  35623. });
  35624. };
  35625. /**
  35626. * Disposes the material
  35627. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35628. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35629. */
  35630. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35631. // Animations
  35632. this.getScene().stopAnimation(this);
  35633. this.getScene().freeProcessedMaterials();
  35634. // Remove from scene
  35635. var index = this._scene.materials.indexOf(this);
  35636. if (index >= 0) {
  35637. this._scene.materials.splice(index, 1);
  35638. }
  35639. // Remove from meshes
  35640. for (index = 0; index < this._scene.meshes.length; index++) {
  35641. var mesh = this._scene.meshes[index];
  35642. if (mesh.material === this) {
  35643. mesh.material = null;
  35644. if (mesh.geometry) {
  35645. var geometry = (mesh.geometry);
  35646. if (this.storeEffectOnSubMeshes) {
  35647. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35648. var subMesh = _a[_i];
  35649. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35650. if (forceDisposeEffect && subMesh._materialEffect) {
  35651. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35652. }
  35653. }
  35654. }
  35655. else {
  35656. geometry._releaseVertexArrayObject(this._effect);
  35657. }
  35658. }
  35659. }
  35660. }
  35661. this._uniformBuffer.dispose();
  35662. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35663. if (forceDisposeEffect && this._effect) {
  35664. if (!this.storeEffectOnSubMeshes) {
  35665. this._scene.getEngine()._releaseEffect(this._effect);
  35666. }
  35667. this._effect = null;
  35668. }
  35669. // Callback
  35670. this.onDisposeObservable.notifyObservers(this);
  35671. this.onDisposeObservable.clear();
  35672. this.onBindObservable.clear();
  35673. this.onUnBindObservable.clear();
  35674. };
  35675. /**
  35676. * Serializes this material
  35677. * @returns the serialized material object
  35678. */
  35679. Material.prototype.serialize = function () {
  35680. return BABYLON.SerializationHelper.Serialize(this);
  35681. };
  35682. /**
  35683. * Creates a MultiMaterial from parsed MultiMaterial data.
  35684. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35685. * @param scene defines the hosting scene
  35686. * @returns a new MultiMaterial
  35687. */
  35688. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35689. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35690. multiMaterial.id = parsedMultiMaterial.id;
  35691. if (BABYLON.Tags) {
  35692. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35693. }
  35694. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35695. var subMatId = parsedMultiMaterial.materials[matIndex];
  35696. if (subMatId) {
  35697. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35698. }
  35699. else {
  35700. multiMaterial.subMaterials.push(null);
  35701. }
  35702. }
  35703. return multiMaterial;
  35704. };
  35705. /**
  35706. * Creates a material from parsed material data
  35707. * @param parsedMaterial defines parsed material data
  35708. * @param scene defines the hosting scene
  35709. * @param rootUrl defines the root URL to use to load textures
  35710. * @returns a new material
  35711. */
  35712. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35713. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35714. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35715. }
  35716. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35717. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35718. if (!BABYLON.LegacyPBRMaterial) {
  35719. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35720. return;
  35721. }
  35722. }
  35723. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35724. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35725. };
  35726. // Triangle views
  35727. Material._TriangleFillMode = 0;
  35728. Material._WireFrameFillMode = 1;
  35729. Material._PointFillMode = 2;
  35730. // Draw modes
  35731. Material._PointListDrawMode = 3;
  35732. Material._LineListDrawMode = 4;
  35733. Material._LineLoopDrawMode = 5;
  35734. Material._LineStripDrawMode = 6;
  35735. Material._TriangleStripDrawMode = 7;
  35736. Material._TriangleFanDrawMode = 8;
  35737. /**
  35738. * Stores the clock-wise side orientation
  35739. */
  35740. Material._ClockWiseSideOrientation = 0;
  35741. /**
  35742. * Stores the counter clock-wise side orientation
  35743. */
  35744. Material._CounterClockWiseSideOrientation = 1;
  35745. /**
  35746. * The dirty texture flag value
  35747. */
  35748. Material._TextureDirtyFlag = 1;
  35749. /**
  35750. * The dirty light flag value
  35751. */
  35752. Material._LightDirtyFlag = 2;
  35753. /**
  35754. * The dirty fresnel flag value
  35755. */
  35756. Material._FresnelDirtyFlag = 4;
  35757. /**
  35758. * The dirty attribute flag value
  35759. */
  35760. Material._AttributesDirtyFlag = 8;
  35761. /**
  35762. * The dirty misc flag value
  35763. */
  35764. Material._MiscDirtyFlag = 16;
  35765. __decorate([
  35766. BABYLON.serialize()
  35767. ], Material.prototype, "id", void 0);
  35768. __decorate([
  35769. BABYLON.serialize()
  35770. ], Material.prototype, "uniqueId", void 0);
  35771. __decorate([
  35772. BABYLON.serialize()
  35773. ], Material.prototype, "name", void 0);
  35774. __decorate([
  35775. BABYLON.serialize()
  35776. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35777. __decorate([
  35778. BABYLON.serialize()
  35779. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35780. __decorate([
  35781. BABYLON.serialize()
  35782. ], Material.prototype, "state", void 0);
  35783. __decorate([
  35784. BABYLON.serialize("alpha")
  35785. ], Material.prototype, "_alpha", void 0);
  35786. __decorate([
  35787. BABYLON.serialize("backFaceCulling")
  35788. ], Material.prototype, "_backFaceCulling", void 0);
  35789. __decorate([
  35790. BABYLON.serialize()
  35791. ], Material.prototype, "sideOrientation", void 0);
  35792. __decorate([
  35793. BABYLON.serialize("alphaMode")
  35794. ], Material.prototype, "_alphaMode", void 0);
  35795. __decorate([
  35796. BABYLON.serialize()
  35797. ], Material.prototype, "_needDepthPrePass", void 0);
  35798. __decorate([
  35799. BABYLON.serialize()
  35800. ], Material.prototype, "disableDepthWrite", void 0);
  35801. __decorate([
  35802. BABYLON.serialize()
  35803. ], Material.prototype, "forceDepthWrite", void 0);
  35804. __decorate([
  35805. BABYLON.serialize()
  35806. ], Material.prototype, "separateCullingPass", void 0);
  35807. __decorate([
  35808. BABYLON.serialize("fogEnabled")
  35809. ], Material.prototype, "_fogEnabled", void 0);
  35810. __decorate([
  35811. BABYLON.serialize()
  35812. ], Material.prototype, "pointSize", void 0);
  35813. __decorate([
  35814. BABYLON.serialize()
  35815. ], Material.prototype, "zOffset", void 0);
  35816. __decorate([
  35817. BABYLON.serialize()
  35818. ], Material.prototype, "wireframe", null);
  35819. __decorate([
  35820. BABYLON.serialize()
  35821. ], Material.prototype, "pointsCloud", null);
  35822. __decorate([
  35823. BABYLON.serialize()
  35824. ], Material.prototype, "fillMode", null);
  35825. return Material;
  35826. }());
  35827. BABYLON.Material = Material;
  35828. })(BABYLON || (BABYLON = {}));
  35829. //# sourceMappingURL=babylon.material.js.map
  35830. var BABYLON;
  35831. (function (BABYLON) {
  35832. var UniformBuffer = /** @class */ (function () {
  35833. /**
  35834. * Uniform buffer objects.
  35835. *
  35836. * Handles blocks of uniform on the GPU.
  35837. *
  35838. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35839. *
  35840. * For more information, please refer to :
  35841. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35842. */
  35843. function UniformBuffer(engine, data, dynamic) {
  35844. this._engine = engine;
  35845. this._noUBO = !engine.supportsUniformBuffers;
  35846. this._dynamic = dynamic;
  35847. this._data = data || [];
  35848. this._uniformLocations = {};
  35849. this._uniformSizes = {};
  35850. this._uniformLocationPointer = 0;
  35851. this._needSync = false;
  35852. if (this._noUBO) {
  35853. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35854. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35855. this.updateFloat = this._updateFloatForEffect;
  35856. this.updateFloat2 = this._updateFloat2ForEffect;
  35857. this.updateFloat3 = this._updateFloat3ForEffect;
  35858. this.updateFloat4 = this._updateFloat4ForEffect;
  35859. this.updateMatrix = this._updateMatrixForEffect;
  35860. this.updateVector3 = this._updateVector3ForEffect;
  35861. this.updateVector4 = this._updateVector4ForEffect;
  35862. this.updateColor3 = this._updateColor3ForEffect;
  35863. this.updateColor4 = this._updateColor4ForEffect;
  35864. }
  35865. else {
  35866. this._engine._uniformBuffers.push(this);
  35867. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35868. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35869. this.updateFloat = this._updateFloatForUniform;
  35870. this.updateFloat2 = this._updateFloat2ForUniform;
  35871. this.updateFloat3 = this._updateFloat3ForUniform;
  35872. this.updateFloat4 = this._updateFloat4ForUniform;
  35873. this.updateMatrix = this._updateMatrixForUniform;
  35874. this.updateVector3 = this._updateVector3ForUniform;
  35875. this.updateVector4 = this._updateVector4ForUniform;
  35876. this.updateColor3 = this._updateColor3ForUniform;
  35877. this.updateColor4 = this._updateColor4ForUniform;
  35878. }
  35879. }
  35880. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35881. // Properties
  35882. /**
  35883. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35884. * or just falling back on setUniformXXX calls.
  35885. */
  35886. get: function () {
  35887. return !this._noUBO;
  35888. },
  35889. enumerable: true,
  35890. configurable: true
  35891. });
  35892. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35893. /**
  35894. * Indicates if the WebGL underlying uniform buffer is in sync
  35895. * with the javascript cache data.
  35896. */
  35897. get: function () {
  35898. return !this._needSync;
  35899. },
  35900. enumerable: true,
  35901. configurable: true
  35902. });
  35903. /**
  35904. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35905. * Also, a dynamic UniformBuffer will disable cache verification and always
  35906. * update the underlying WebGL uniform buffer to the GPU.
  35907. */
  35908. UniformBuffer.prototype.isDynamic = function () {
  35909. return this._dynamic !== undefined;
  35910. };
  35911. /**
  35912. * The data cache on JS side.
  35913. */
  35914. UniformBuffer.prototype.getData = function () {
  35915. return this._bufferData;
  35916. };
  35917. /**
  35918. * The underlying WebGL Uniform buffer.
  35919. */
  35920. UniformBuffer.prototype.getBuffer = function () {
  35921. return this._buffer;
  35922. };
  35923. /**
  35924. * std140 layout specifies how to align data within an UBO structure.
  35925. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35926. * for specs.
  35927. */
  35928. UniformBuffer.prototype._fillAlignment = function (size) {
  35929. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35930. // and 4x4 matrices
  35931. // TODO : change if other types are used
  35932. var alignment;
  35933. if (size <= 2) {
  35934. alignment = size;
  35935. }
  35936. else {
  35937. alignment = 4;
  35938. }
  35939. if ((this._uniformLocationPointer % alignment) !== 0) {
  35940. var oldPointer = this._uniformLocationPointer;
  35941. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35942. var diff = this._uniformLocationPointer - oldPointer;
  35943. for (var i = 0; i < diff; i++) {
  35944. this._data.push(0);
  35945. }
  35946. }
  35947. };
  35948. /**
  35949. * Adds an uniform in the buffer.
  35950. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35951. * for the layout to be correct !
  35952. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35953. * @param {number|number[]} size Data size, or data directly.
  35954. */
  35955. UniformBuffer.prototype.addUniform = function (name, size) {
  35956. if (this._noUBO) {
  35957. return;
  35958. }
  35959. if (this._uniformLocations[name] !== undefined) {
  35960. // Already existing uniform
  35961. return;
  35962. }
  35963. // This function must be called in the order of the shader layout !
  35964. // size can be the size of the uniform, or data directly
  35965. var data;
  35966. if (size instanceof Array) {
  35967. data = size;
  35968. size = data.length;
  35969. }
  35970. else {
  35971. size = size;
  35972. data = [];
  35973. // Fill with zeros
  35974. for (var i = 0; i < size; i++) {
  35975. data.push(0);
  35976. }
  35977. }
  35978. this._fillAlignment(size);
  35979. this._uniformSizes[name] = size;
  35980. this._uniformLocations[name] = this._uniformLocationPointer;
  35981. this._uniformLocationPointer += size;
  35982. for (var i = 0; i < size; i++) {
  35983. this._data.push(data[i]);
  35984. }
  35985. this._needSync = true;
  35986. };
  35987. /**
  35988. * Wrapper for addUniform.
  35989. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35990. * @param {Matrix} mat A 4x4 matrix.
  35991. */
  35992. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35993. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35994. };
  35995. /**
  35996. * Wrapper for addUniform.
  35997. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35998. * @param {number} x
  35999. * @param {number} y
  36000. */
  36001. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36002. var temp = [x, y];
  36003. this.addUniform(name, temp);
  36004. };
  36005. /**
  36006. * Wrapper for addUniform.
  36007. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36008. * @param {number} x
  36009. * @param {number} y
  36010. * @param {number} z
  36011. */
  36012. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36013. var temp = [x, y, z];
  36014. this.addUniform(name, temp);
  36015. };
  36016. /**
  36017. * Wrapper for addUniform.
  36018. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36019. * @param {Color3} color
  36020. */
  36021. UniformBuffer.prototype.addColor3 = function (name, color) {
  36022. var temp = new Array();
  36023. color.toArray(temp);
  36024. this.addUniform(name, temp);
  36025. };
  36026. /**
  36027. * Wrapper for addUniform.
  36028. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36029. * @param {Color3} color
  36030. * @param {number} alpha
  36031. */
  36032. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36033. var temp = new Array();
  36034. color.toArray(temp);
  36035. temp.push(alpha);
  36036. this.addUniform(name, temp);
  36037. };
  36038. /**
  36039. * Wrapper for addUniform.
  36040. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36041. * @param {Vector3} vector
  36042. */
  36043. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36044. var temp = new Array();
  36045. vector.toArray(temp);
  36046. this.addUniform(name, temp);
  36047. };
  36048. /**
  36049. * Wrapper for addUniform.
  36050. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36051. */
  36052. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36053. this.addUniform(name, 12);
  36054. };
  36055. /**
  36056. * Wrapper for addUniform.
  36057. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36058. */
  36059. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36060. this.addUniform(name, 8);
  36061. };
  36062. /**
  36063. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36064. */
  36065. UniformBuffer.prototype.create = function () {
  36066. if (this._noUBO) {
  36067. return;
  36068. }
  36069. if (this._buffer) {
  36070. return; // nothing to do
  36071. }
  36072. // See spec, alignment must be filled as a vec4
  36073. this._fillAlignment(4);
  36074. this._bufferData = new Float32Array(this._data);
  36075. this._rebuild();
  36076. this._needSync = true;
  36077. };
  36078. UniformBuffer.prototype._rebuild = function () {
  36079. if (this._noUBO) {
  36080. return;
  36081. }
  36082. if (this._dynamic) {
  36083. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36084. }
  36085. else {
  36086. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36087. }
  36088. };
  36089. /**
  36090. * Updates the WebGL Uniform Buffer on the GPU.
  36091. * If the `dynamic` flag is set to true, no cache comparison is done.
  36092. * Otherwise, the buffer will be updated only if the cache differs.
  36093. */
  36094. UniformBuffer.prototype.update = function () {
  36095. if (!this._buffer) {
  36096. this.create();
  36097. return;
  36098. }
  36099. if (!this._dynamic && !this._needSync) {
  36100. return;
  36101. }
  36102. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36103. this._needSync = false;
  36104. };
  36105. /**
  36106. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36107. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36108. * @param {number[]|Float32Array} data Flattened data
  36109. * @param {number} size Size of the data.
  36110. */
  36111. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36112. var location = this._uniformLocations[uniformName];
  36113. if (location === undefined) {
  36114. if (this._buffer) {
  36115. // Cannot add an uniform if the buffer is already created
  36116. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36117. return;
  36118. }
  36119. this.addUniform(uniformName, size);
  36120. location = this._uniformLocations[uniformName];
  36121. }
  36122. if (!this._buffer) {
  36123. this.create();
  36124. }
  36125. if (!this._dynamic) {
  36126. // Cache for static uniform buffers
  36127. var changed = false;
  36128. for (var i = 0; i < size; i++) {
  36129. if (this._bufferData[location + i] !== data[i]) {
  36130. changed = true;
  36131. this._bufferData[location + i] = data[i];
  36132. }
  36133. }
  36134. this._needSync = this._needSync || changed;
  36135. }
  36136. else {
  36137. // No cache for dynamic
  36138. for (var i = 0; i < size; i++) {
  36139. this._bufferData[location + i] = data[i];
  36140. }
  36141. }
  36142. };
  36143. // Update methods
  36144. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36145. // To match std140, matrix must be realigned
  36146. for (var i = 0; i < 3; i++) {
  36147. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36148. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36149. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36150. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36151. }
  36152. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36153. };
  36154. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36155. this._currentEffect.setMatrix3x3(name, matrix);
  36156. };
  36157. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36158. this._currentEffect.setMatrix2x2(name, matrix);
  36159. };
  36160. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36161. // To match std140, matrix must be realigned
  36162. for (var i = 0; i < 2; i++) {
  36163. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36164. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36165. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36166. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36167. }
  36168. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36169. };
  36170. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36171. this._currentEffect.setFloat(name, x);
  36172. };
  36173. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36174. UniformBuffer._tempBuffer[0] = x;
  36175. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36176. };
  36177. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36178. if (suffix === void 0) { suffix = ""; }
  36179. this._currentEffect.setFloat2(name + suffix, x, y);
  36180. };
  36181. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36182. if (suffix === void 0) { suffix = ""; }
  36183. UniformBuffer._tempBuffer[0] = x;
  36184. UniformBuffer._tempBuffer[1] = y;
  36185. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36186. };
  36187. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36188. if (suffix === void 0) { suffix = ""; }
  36189. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36190. };
  36191. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36192. if (suffix === void 0) { suffix = ""; }
  36193. UniformBuffer._tempBuffer[0] = x;
  36194. UniformBuffer._tempBuffer[1] = y;
  36195. UniformBuffer._tempBuffer[2] = z;
  36196. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36197. };
  36198. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36199. if (suffix === void 0) { suffix = ""; }
  36200. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36201. };
  36202. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36203. if (suffix === void 0) { suffix = ""; }
  36204. UniformBuffer._tempBuffer[0] = x;
  36205. UniformBuffer._tempBuffer[1] = y;
  36206. UniformBuffer._tempBuffer[2] = z;
  36207. UniformBuffer._tempBuffer[3] = w;
  36208. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36209. };
  36210. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36211. this._currentEffect.setMatrix(name, mat);
  36212. };
  36213. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36214. this.updateUniform(name, mat.toArray(), 16);
  36215. };
  36216. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36217. this._currentEffect.setVector3(name, vector);
  36218. };
  36219. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36220. vector.toArray(UniformBuffer._tempBuffer);
  36221. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36222. };
  36223. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36224. this._currentEffect.setVector4(name, vector);
  36225. };
  36226. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36227. vector.toArray(UniformBuffer._tempBuffer);
  36228. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36229. };
  36230. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36231. if (suffix === void 0) { suffix = ""; }
  36232. this._currentEffect.setColor3(name + suffix, color);
  36233. };
  36234. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36235. if (suffix === void 0) { suffix = ""; }
  36236. color.toArray(UniformBuffer._tempBuffer);
  36237. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36238. };
  36239. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36240. if (suffix === void 0) { suffix = ""; }
  36241. this._currentEffect.setColor4(name + suffix, color, alpha);
  36242. };
  36243. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36244. if (suffix === void 0) { suffix = ""; }
  36245. color.toArray(UniformBuffer._tempBuffer);
  36246. UniformBuffer._tempBuffer[3] = alpha;
  36247. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36248. };
  36249. /**
  36250. * Sets a sampler uniform on the effect.
  36251. * @param {string} name Name of the sampler.
  36252. * @param {Texture} texture
  36253. */
  36254. UniformBuffer.prototype.setTexture = function (name, texture) {
  36255. this._currentEffect.setTexture(name, texture);
  36256. };
  36257. /**
  36258. * Directly updates the value of the uniform in the cache AND on the GPU.
  36259. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36260. * @param {number[]|Float32Array} data Flattened data
  36261. */
  36262. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36263. this.updateUniform(uniformName, data, data.length);
  36264. this.update();
  36265. };
  36266. /**
  36267. * Binds this uniform buffer to an effect.
  36268. * @param {Effect} effect
  36269. * @param {string} name Name of the uniform block in the shader.
  36270. */
  36271. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36272. this._currentEffect = effect;
  36273. if (this._noUBO || !this._buffer) {
  36274. return;
  36275. }
  36276. effect.bindUniformBuffer(this._buffer, name);
  36277. };
  36278. /**
  36279. * Disposes the uniform buffer.
  36280. */
  36281. UniformBuffer.prototype.dispose = function () {
  36282. if (this._noUBO) {
  36283. return;
  36284. }
  36285. var index = this._engine._uniformBuffers.indexOf(this);
  36286. if (index !== -1) {
  36287. this._engine._uniformBuffers.splice(index, 1);
  36288. }
  36289. if (!this._buffer) {
  36290. return;
  36291. }
  36292. if (this._engine._releaseBuffer(this._buffer)) {
  36293. this._buffer = null;
  36294. }
  36295. };
  36296. // Pool for avoiding memory leaks
  36297. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36298. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36299. return UniformBuffer;
  36300. }());
  36301. BABYLON.UniformBuffer = UniformBuffer;
  36302. })(BABYLON || (BABYLON = {}));
  36303. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36304. var BABYLON;
  36305. (function (BABYLON) {
  36306. /**
  36307. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36308. */
  36309. var VertexData = /** @class */ (function () {
  36310. function VertexData() {
  36311. }
  36312. /**
  36313. * Uses the passed data array to set the set the values for the specified kind of data
  36314. * @param data a linear array of floating numbers
  36315. * @param kind the type of data that is being set, eg positions, colors etc
  36316. */
  36317. VertexData.prototype.set = function (data, kind) {
  36318. switch (kind) {
  36319. case BABYLON.VertexBuffer.PositionKind:
  36320. this.positions = data;
  36321. break;
  36322. case BABYLON.VertexBuffer.NormalKind:
  36323. this.normals = data;
  36324. break;
  36325. case BABYLON.VertexBuffer.TangentKind:
  36326. this.tangents = data;
  36327. break;
  36328. case BABYLON.VertexBuffer.UVKind:
  36329. this.uvs = data;
  36330. break;
  36331. case BABYLON.VertexBuffer.UV2Kind:
  36332. this.uvs2 = data;
  36333. break;
  36334. case BABYLON.VertexBuffer.UV3Kind:
  36335. this.uvs3 = data;
  36336. break;
  36337. case BABYLON.VertexBuffer.UV4Kind:
  36338. this.uvs4 = data;
  36339. break;
  36340. case BABYLON.VertexBuffer.UV5Kind:
  36341. this.uvs5 = data;
  36342. break;
  36343. case BABYLON.VertexBuffer.UV6Kind:
  36344. this.uvs6 = data;
  36345. break;
  36346. case BABYLON.VertexBuffer.ColorKind:
  36347. this.colors = data;
  36348. break;
  36349. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36350. this.matricesIndices = data;
  36351. break;
  36352. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36353. this.matricesWeights = data;
  36354. break;
  36355. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36356. this.matricesIndicesExtra = data;
  36357. break;
  36358. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36359. this.matricesWeightsExtra = data;
  36360. break;
  36361. }
  36362. };
  36363. /**
  36364. * Associates the vertexData to the passed Mesh.
  36365. * Sets it as updatable or not (default `false`)
  36366. * @param mesh the mesh the vertexData is applied to
  36367. * @param updatable when used and having the value true allows new data to update the vertexData
  36368. * @returns the VertexData
  36369. */
  36370. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36371. this._applyTo(mesh, updatable);
  36372. return this;
  36373. };
  36374. /**
  36375. * Associates the vertexData to the passed Geometry.
  36376. * Sets it as updatable or not (default `false`)
  36377. * @param geometry the geometry the vertexData is applied to
  36378. * @param updatable when used and having the value true allows new data to update the vertexData
  36379. * @returns VertexData
  36380. */
  36381. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36382. this._applyTo(geometry, updatable);
  36383. return this;
  36384. };
  36385. /**
  36386. * Updates the associated mesh
  36387. * @param mesh the mesh to be updated
  36388. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36389. * @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
  36390. * @returns VertexData
  36391. */
  36392. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36393. this._update(mesh);
  36394. return this;
  36395. };
  36396. /**
  36397. * Updates the associated geometry
  36398. * @param geometry the geometry to be updated
  36399. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36400. * @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
  36401. * @returns VertexData.
  36402. */
  36403. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36404. this._update(geometry);
  36405. return this;
  36406. };
  36407. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36408. if (updatable === void 0) { updatable = false; }
  36409. if (this.positions) {
  36410. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36411. }
  36412. if (this.normals) {
  36413. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36414. }
  36415. if (this.tangents) {
  36416. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36417. }
  36418. if (this.uvs) {
  36419. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36420. }
  36421. if (this.uvs2) {
  36422. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36423. }
  36424. if (this.uvs3) {
  36425. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36426. }
  36427. if (this.uvs4) {
  36428. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36429. }
  36430. if (this.uvs5) {
  36431. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36432. }
  36433. if (this.uvs6) {
  36434. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36435. }
  36436. if (this.colors) {
  36437. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36438. }
  36439. if (this.matricesIndices) {
  36440. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36441. }
  36442. if (this.matricesWeights) {
  36443. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36444. }
  36445. if (this.matricesIndicesExtra) {
  36446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36447. }
  36448. if (this.matricesWeightsExtra) {
  36449. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36450. }
  36451. if (this.indices) {
  36452. meshOrGeometry.setIndices(this.indices, null, updatable);
  36453. }
  36454. return this;
  36455. };
  36456. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36457. if (this.positions) {
  36458. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36459. }
  36460. if (this.normals) {
  36461. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36462. }
  36463. if (this.tangents) {
  36464. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36465. }
  36466. if (this.uvs) {
  36467. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36468. }
  36469. if (this.uvs2) {
  36470. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36471. }
  36472. if (this.uvs3) {
  36473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36474. }
  36475. if (this.uvs4) {
  36476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36477. }
  36478. if (this.uvs5) {
  36479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36480. }
  36481. if (this.uvs6) {
  36482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36483. }
  36484. if (this.colors) {
  36485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36486. }
  36487. if (this.matricesIndices) {
  36488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36489. }
  36490. if (this.matricesWeights) {
  36491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36492. }
  36493. if (this.matricesIndicesExtra) {
  36494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36495. }
  36496. if (this.matricesWeightsExtra) {
  36497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36498. }
  36499. if (this.indices) {
  36500. meshOrGeometry.setIndices(this.indices, null);
  36501. }
  36502. return this;
  36503. };
  36504. /**
  36505. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36506. * @param matrix the transforming matrix
  36507. * @returns the VertexData
  36508. */
  36509. VertexData.prototype.transform = function (matrix) {
  36510. var transformed = BABYLON.Vector3.Zero();
  36511. var index;
  36512. if (this.positions) {
  36513. var position = BABYLON.Vector3.Zero();
  36514. for (index = 0; index < this.positions.length; index += 3) {
  36515. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36516. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36517. this.positions[index] = transformed.x;
  36518. this.positions[index + 1] = transformed.y;
  36519. this.positions[index + 2] = transformed.z;
  36520. }
  36521. }
  36522. if (this.normals) {
  36523. var normal = BABYLON.Vector3.Zero();
  36524. for (index = 0; index < this.normals.length; index += 3) {
  36525. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36526. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36527. this.normals[index] = transformed.x;
  36528. this.normals[index + 1] = transformed.y;
  36529. this.normals[index + 2] = transformed.z;
  36530. }
  36531. }
  36532. if (this.tangents) {
  36533. var tangent = BABYLON.Vector4.Zero();
  36534. var tangentTransformed = BABYLON.Vector4.Zero();
  36535. for (index = 0; index < this.tangents.length; index += 4) {
  36536. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36537. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36538. this.tangents[index] = tangentTransformed.x;
  36539. this.tangents[index + 1] = tangentTransformed.y;
  36540. this.tangents[index + 2] = tangentTransformed.z;
  36541. this.tangents[index + 3] = tangentTransformed.w;
  36542. }
  36543. }
  36544. return this;
  36545. };
  36546. /**
  36547. * Merges the passed VertexData into the current one
  36548. * @param other the VertexData to be merged into the current one
  36549. * @returns the modified VertexData
  36550. */
  36551. VertexData.prototype.merge = function (other) {
  36552. this._validate();
  36553. other._validate();
  36554. if (!this.normals !== !other.normals ||
  36555. !this.tangents !== !other.tangents ||
  36556. !this.uvs !== !other.uvs ||
  36557. !this.uvs2 !== !other.uvs2 ||
  36558. !this.uvs3 !== !other.uvs3 ||
  36559. !this.uvs4 !== !other.uvs4 ||
  36560. !this.uvs5 !== !other.uvs5 ||
  36561. !this.uvs6 !== !other.uvs6 ||
  36562. !this.colors !== !other.colors ||
  36563. !this.matricesIndices !== !other.matricesIndices ||
  36564. !this.matricesWeights !== !other.matricesWeights ||
  36565. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36566. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36567. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36568. }
  36569. if (other.indices) {
  36570. if (!this.indices) {
  36571. this.indices = [];
  36572. }
  36573. var offset = this.positions ? this.positions.length / 3 : 0;
  36574. for (var index = 0; index < other.indices.length; index++) {
  36575. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36576. this.indices.push(other.indices[index] + offset);
  36577. }
  36578. }
  36579. this.positions = this._mergeElement(this.positions, other.positions);
  36580. this.normals = this._mergeElement(this.normals, other.normals);
  36581. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36582. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36583. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36584. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36585. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36586. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36587. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36588. this.colors = this._mergeElement(this.colors, other.colors);
  36589. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36590. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36591. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36592. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36593. return this;
  36594. };
  36595. VertexData.prototype._mergeElement = function (source, other) {
  36596. if (!source) {
  36597. return other;
  36598. }
  36599. if (!other) {
  36600. return source;
  36601. }
  36602. var len = other.length + source.length;
  36603. var isSrcTypedArray = source instanceof Float32Array;
  36604. var isOthTypedArray = other instanceof Float32Array;
  36605. // use non-loop method when the source is Float32Array
  36606. if (isSrcTypedArray) {
  36607. var ret32 = new Float32Array(len);
  36608. ret32.set(source);
  36609. ret32.set(other, source.length);
  36610. return ret32;
  36611. // source is number[], when other is also use concat
  36612. }
  36613. else if (!isOthTypedArray) {
  36614. return source.concat(other);
  36615. // source is a number[], but other is a Float32Array, loop required
  36616. }
  36617. else {
  36618. var ret = source.slice(0); // copy source to a separate array
  36619. for (var i = 0, len = other.length; i < len; i++) {
  36620. ret.push(other[i]);
  36621. }
  36622. return ret;
  36623. }
  36624. };
  36625. VertexData.prototype._validate = function () {
  36626. if (!this.positions) {
  36627. throw new Error("Positions are required");
  36628. }
  36629. var getElementCount = function (kind, values) {
  36630. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36631. if ((values.length % stride) !== 0) {
  36632. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36633. }
  36634. return values.length / stride;
  36635. };
  36636. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36637. var validateElementCount = function (kind, values) {
  36638. var elementCount = getElementCount(kind, values);
  36639. if (elementCount !== positionsElementCount) {
  36640. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36641. }
  36642. };
  36643. if (this.normals)
  36644. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36645. if (this.tangents)
  36646. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36647. if (this.uvs)
  36648. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36649. if (this.uvs2)
  36650. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36651. if (this.uvs3)
  36652. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36653. if (this.uvs4)
  36654. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36655. if (this.uvs5)
  36656. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36657. if (this.uvs6)
  36658. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36659. if (this.colors)
  36660. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36661. if (this.matricesIndices)
  36662. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36663. if (this.matricesWeights)
  36664. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36665. if (this.matricesIndicesExtra)
  36666. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36667. if (this.matricesWeightsExtra)
  36668. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36669. };
  36670. /**
  36671. * Serializes the VertexData
  36672. * @returns a serialized object
  36673. */
  36674. VertexData.prototype.serialize = function () {
  36675. var serializationObject = this.serialize();
  36676. if (this.positions) {
  36677. serializationObject.positions = this.positions;
  36678. }
  36679. if (this.normals) {
  36680. serializationObject.normals = this.normals;
  36681. }
  36682. if (this.tangents) {
  36683. serializationObject.tangents = this.tangents;
  36684. }
  36685. if (this.uvs) {
  36686. serializationObject.uvs = this.uvs;
  36687. }
  36688. if (this.uvs2) {
  36689. serializationObject.uvs2 = this.uvs2;
  36690. }
  36691. if (this.uvs3) {
  36692. serializationObject.uvs3 = this.uvs3;
  36693. }
  36694. if (this.uvs4) {
  36695. serializationObject.uvs4 = this.uvs4;
  36696. }
  36697. if (this.uvs5) {
  36698. serializationObject.uvs5 = this.uvs5;
  36699. }
  36700. if (this.uvs6) {
  36701. serializationObject.uvs6 = this.uvs6;
  36702. }
  36703. if (this.colors) {
  36704. serializationObject.colors = this.colors;
  36705. }
  36706. if (this.matricesIndices) {
  36707. serializationObject.matricesIndices = this.matricesIndices;
  36708. serializationObject.matricesIndices._isExpanded = true;
  36709. }
  36710. if (this.matricesWeights) {
  36711. serializationObject.matricesWeights = this.matricesWeights;
  36712. }
  36713. if (this.matricesIndicesExtra) {
  36714. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36715. serializationObject.matricesIndicesExtra._isExpanded = true;
  36716. }
  36717. if (this.matricesWeightsExtra) {
  36718. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36719. }
  36720. serializationObject.indices = this.indices;
  36721. return serializationObject;
  36722. };
  36723. // Statics
  36724. /**
  36725. * Extracts the vertexData from a mesh
  36726. * @param mesh the mesh from which to extract the VertexData
  36727. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36728. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36729. * @returns the object VertexData associated to the passed mesh
  36730. */
  36731. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36732. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36733. };
  36734. /**
  36735. * Extracts the vertexData from the geometry
  36736. * @param geometry the geometry from which to extract the VertexData
  36737. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36738. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36739. * @returns the object VertexData associated to the passed mesh
  36740. */
  36741. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36742. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36743. };
  36744. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36745. var result = new VertexData();
  36746. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36747. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36748. }
  36749. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36750. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36751. }
  36752. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36753. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36754. }
  36755. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36756. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36757. }
  36758. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36759. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36760. }
  36761. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36762. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36763. }
  36764. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36765. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36766. }
  36767. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36768. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36769. }
  36770. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36771. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36772. }
  36773. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36774. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36775. }
  36776. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36777. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36778. }
  36779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36780. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36781. }
  36782. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36783. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36784. }
  36785. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36786. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36787. }
  36788. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36789. return result;
  36790. };
  36791. /**
  36792. * Creates the VertexData for a Ribbon
  36793. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36794. * * pathArray array of paths, each of which an array of successive Vector3
  36795. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36796. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36797. * * 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
  36798. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36799. * * 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)
  36800. * * 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)
  36801. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36802. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36803. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36804. * @returns the VertexData of the ribbon
  36805. */
  36806. VertexData.CreateRibbon = function (options) {
  36807. var pathArray = options.pathArray;
  36808. var closeArray = options.closeArray || false;
  36809. var closePath = options.closePath || false;
  36810. var invertUV = options.invertUV || false;
  36811. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36812. var offset = options.offset || defaultOffset;
  36813. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36814. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36815. var customUV = options.uvs;
  36816. var customColors = options.colors;
  36817. var positions = [];
  36818. var indices = [];
  36819. var normals = [];
  36820. var uvs = [];
  36821. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36822. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36823. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36824. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36825. var minlg; // minimal length among all paths from pathArray
  36826. var lg = []; // array of path lengths : nb of vertex per path
  36827. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36828. var p; // path iterator
  36829. var i; // point iterator
  36830. var j; // point iterator
  36831. // if single path in pathArray
  36832. if (pathArray.length < 2) {
  36833. var ar1 = [];
  36834. var ar2 = [];
  36835. for (i = 0; i < pathArray[0].length - offset; i++) {
  36836. ar1.push(pathArray[0][i]);
  36837. ar2.push(pathArray[0][i + offset]);
  36838. }
  36839. pathArray = [ar1, ar2];
  36840. }
  36841. // positions and horizontal distances (u)
  36842. var idc = 0;
  36843. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36844. var path;
  36845. var l;
  36846. minlg = pathArray[0].length;
  36847. var vectlg;
  36848. var dist;
  36849. for (p = 0; p < pathArray.length; p++) {
  36850. uTotalDistance[p] = 0;
  36851. us[p] = [0];
  36852. path = pathArray[p];
  36853. l = path.length;
  36854. minlg = (minlg < l) ? minlg : l;
  36855. j = 0;
  36856. while (j < l) {
  36857. positions.push(path[j].x, path[j].y, path[j].z);
  36858. if (j > 0) {
  36859. vectlg = path[j].subtract(path[j - 1]).length();
  36860. dist = vectlg + uTotalDistance[p];
  36861. us[p].push(dist);
  36862. uTotalDistance[p] = dist;
  36863. }
  36864. j++;
  36865. }
  36866. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36867. j--;
  36868. positions.push(path[0].x, path[0].y, path[0].z);
  36869. vectlg = path[j].subtract(path[0]).length();
  36870. dist = vectlg + uTotalDistance[p];
  36871. us[p].push(dist);
  36872. uTotalDistance[p] = dist;
  36873. }
  36874. lg[p] = l + closePathCorr;
  36875. idx[p] = idc;
  36876. idc += (l + closePathCorr);
  36877. }
  36878. // vertical distances (v)
  36879. var path1;
  36880. var path2;
  36881. var vertex1 = null;
  36882. var vertex2 = null;
  36883. for (i = 0; i < minlg + closePathCorr; i++) {
  36884. vTotalDistance[i] = 0;
  36885. vs[i] = [0];
  36886. for (p = 0; p < pathArray.length - 1; p++) {
  36887. path1 = pathArray[p];
  36888. path2 = pathArray[p + 1];
  36889. if (i === minlg) { // closePath
  36890. vertex1 = path1[0];
  36891. vertex2 = path2[0];
  36892. }
  36893. else {
  36894. vertex1 = path1[i];
  36895. vertex2 = path2[i];
  36896. }
  36897. vectlg = vertex2.subtract(vertex1).length();
  36898. dist = vectlg + vTotalDistance[i];
  36899. vs[i].push(dist);
  36900. vTotalDistance[i] = dist;
  36901. }
  36902. if (closeArray && vertex2 && vertex1) {
  36903. path1 = pathArray[p];
  36904. path2 = pathArray[0];
  36905. if (i === minlg) { // closePath
  36906. vertex2 = path2[0];
  36907. }
  36908. vectlg = vertex2.subtract(vertex1).length();
  36909. dist = vectlg + vTotalDistance[i];
  36910. vTotalDistance[i] = dist;
  36911. }
  36912. }
  36913. // uvs
  36914. var u;
  36915. var v;
  36916. if (customUV) {
  36917. for (p = 0; p < customUV.length; p++) {
  36918. uvs.push(customUV[p].x, customUV[p].y);
  36919. }
  36920. }
  36921. else {
  36922. for (p = 0; p < pathArray.length; p++) {
  36923. for (i = 0; i < minlg + closePathCorr; i++) {
  36924. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36925. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36926. if (invertUV) {
  36927. uvs.push(v, u);
  36928. }
  36929. else {
  36930. uvs.push(u, v);
  36931. }
  36932. }
  36933. }
  36934. }
  36935. // indices
  36936. p = 0; // path index
  36937. var pi = 0; // positions array index
  36938. var l1 = lg[p] - 1; // path1 length
  36939. var l2 = lg[p + 1] - 1; // path2 length
  36940. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36941. var shft = idx[1] - idx[0]; // shift
  36942. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36943. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36944. // 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
  36945. indices.push(pi, pi + shft, pi + 1);
  36946. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36947. pi += 1;
  36948. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36949. p++;
  36950. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36951. shft = idx[0] - idx[p];
  36952. l1 = lg[p] - 1;
  36953. l2 = lg[0] - 1;
  36954. }
  36955. else {
  36956. shft = idx[p + 1] - idx[p];
  36957. l1 = lg[p] - 1;
  36958. l2 = lg[p + 1] - 1;
  36959. }
  36960. pi = idx[p];
  36961. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36962. }
  36963. }
  36964. // normals
  36965. VertexData.ComputeNormals(positions, indices, normals);
  36966. if (closePath) { // update both the first and last vertex normals to their average value
  36967. var indexFirst = 0;
  36968. var indexLast = 0;
  36969. for (p = 0; p < pathArray.length; p++) {
  36970. indexFirst = idx[p] * 3;
  36971. if (p + 1 < pathArray.length) {
  36972. indexLast = (idx[p + 1] - 1) * 3;
  36973. }
  36974. else {
  36975. indexLast = normals.length - 3;
  36976. }
  36977. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36978. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36979. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36980. normals[indexLast] = normals[indexFirst];
  36981. normals[indexLast + 1] = normals[indexFirst + 1];
  36982. normals[indexLast + 2] = normals[indexFirst + 2];
  36983. }
  36984. }
  36985. // sides
  36986. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36987. // Colors
  36988. var colors = null;
  36989. if (customColors) {
  36990. colors = new Float32Array(customColors.length * 4);
  36991. for (var c = 0; c < customColors.length; c++) {
  36992. colors[c * 4] = customColors[c].r;
  36993. colors[c * 4 + 1] = customColors[c].g;
  36994. colors[c * 4 + 2] = customColors[c].b;
  36995. colors[c * 4 + 3] = customColors[c].a;
  36996. }
  36997. }
  36998. // Result
  36999. var vertexData = new VertexData();
  37000. var positions32 = new Float32Array(positions);
  37001. var normals32 = new Float32Array(normals);
  37002. var uvs32 = new Float32Array(uvs);
  37003. vertexData.indices = indices;
  37004. vertexData.positions = positions32;
  37005. vertexData.normals = normals32;
  37006. vertexData.uvs = uvs32;
  37007. if (colors) {
  37008. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37009. }
  37010. if (closePath) {
  37011. vertexData._idx = idx;
  37012. }
  37013. return vertexData;
  37014. };
  37015. /**
  37016. * Creates the VertexData for a box
  37017. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37018. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37019. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37020. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37021. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37022. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37023. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37024. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37025. * * 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)
  37026. * * 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)
  37027. * @returns the VertexData of the box
  37028. */
  37029. VertexData.CreateBox = function (options) {
  37030. var normalsSource = [
  37031. new BABYLON.Vector3(0, 0, 1),
  37032. new BABYLON.Vector3(0, 0, -1),
  37033. new BABYLON.Vector3(1, 0, 0),
  37034. new BABYLON.Vector3(-1, 0, 0),
  37035. new BABYLON.Vector3(0, 1, 0),
  37036. new BABYLON.Vector3(0, -1, 0)
  37037. ];
  37038. var indices = [];
  37039. var positions = [];
  37040. var normals = [];
  37041. var uvs = [];
  37042. var width = options.width || options.size || 1;
  37043. var height = options.height || options.size || 1;
  37044. var depth = options.depth || options.size || 1;
  37045. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37046. var faceUV = options.faceUV || new Array(6);
  37047. var faceColors = options.faceColors;
  37048. var colors = [];
  37049. // default face colors and UV if undefined
  37050. for (var f = 0; f < 6; f++) {
  37051. if (faceUV[f] === undefined) {
  37052. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37053. }
  37054. if (faceColors && faceColors[f] === undefined) {
  37055. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37056. }
  37057. }
  37058. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37059. // Create each face in turn.
  37060. for (var index = 0; index < normalsSource.length; index++) {
  37061. var normal = normalsSource[index];
  37062. // Get two vectors perpendicular to the face normal and to each other.
  37063. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37064. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37065. // Six indices (two triangles) per face.
  37066. var verticesLength = positions.length / 3;
  37067. indices.push(verticesLength);
  37068. indices.push(verticesLength + 1);
  37069. indices.push(verticesLength + 2);
  37070. indices.push(verticesLength);
  37071. indices.push(verticesLength + 2);
  37072. indices.push(verticesLength + 3);
  37073. // Four vertices per face.
  37074. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37075. positions.push(vertex.x, vertex.y, vertex.z);
  37076. normals.push(normal.x, normal.y, normal.z);
  37077. uvs.push(faceUV[index].z, faceUV[index].w);
  37078. if (faceColors) {
  37079. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37080. }
  37081. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37082. positions.push(vertex.x, vertex.y, vertex.z);
  37083. normals.push(normal.x, normal.y, normal.z);
  37084. uvs.push(faceUV[index].x, faceUV[index].w);
  37085. if (faceColors) {
  37086. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37087. }
  37088. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37089. positions.push(vertex.x, vertex.y, vertex.z);
  37090. normals.push(normal.x, normal.y, normal.z);
  37091. uvs.push(faceUV[index].x, faceUV[index].y);
  37092. if (faceColors) {
  37093. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37094. }
  37095. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37096. positions.push(vertex.x, vertex.y, vertex.z);
  37097. normals.push(normal.x, normal.y, normal.z);
  37098. uvs.push(faceUV[index].z, faceUV[index].y);
  37099. if (faceColors) {
  37100. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37101. }
  37102. }
  37103. // sides
  37104. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37105. // Result
  37106. var vertexData = new VertexData();
  37107. vertexData.indices = indices;
  37108. vertexData.positions = positions;
  37109. vertexData.normals = normals;
  37110. vertexData.uvs = uvs;
  37111. if (faceColors) {
  37112. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37113. vertexData.colors = totalColors;
  37114. }
  37115. return vertexData;
  37116. };
  37117. /**
  37118. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37119. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37120. * * segments sets the number of horizontal strips optional, default 32
  37121. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37122. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37123. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37124. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37125. * * 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
  37126. * * 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
  37127. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37128. * * 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)
  37129. * * 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)
  37130. * @returns the VertexData of the ellipsoid
  37131. */
  37132. VertexData.CreateSphere = function (options) {
  37133. var segments = options.segments || 32;
  37134. var diameterX = options.diameterX || options.diameter || 1;
  37135. var diameterY = options.diameterY || options.diameter || 1;
  37136. var diameterZ = options.diameterZ || options.diameter || 1;
  37137. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37138. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37139. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37140. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37141. var totalZRotationSteps = 2 + segments;
  37142. var totalYRotationSteps = 2 * totalZRotationSteps;
  37143. var indices = [];
  37144. var positions = [];
  37145. var normals = [];
  37146. var uvs = [];
  37147. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37148. var normalizedZ = zRotationStep / totalZRotationSteps;
  37149. var angleZ = normalizedZ * Math.PI * slice;
  37150. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37151. var normalizedY = yRotationStep / totalYRotationSteps;
  37152. var angleY = normalizedY * Math.PI * 2 * arc;
  37153. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37154. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37155. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37156. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37157. var vertex = complete.multiply(radius);
  37158. var normal = complete.divide(radius).normalize();
  37159. positions.push(vertex.x, vertex.y, vertex.z);
  37160. normals.push(normal.x, normal.y, normal.z);
  37161. uvs.push(normalizedY, normalizedZ);
  37162. }
  37163. if (zRotationStep > 0) {
  37164. var verticesCount = positions.length / 3;
  37165. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37166. indices.push((firstIndex));
  37167. indices.push((firstIndex + 1));
  37168. indices.push(firstIndex + totalYRotationSteps + 1);
  37169. indices.push((firstIndex + totalYRotationSteps + 1));
  37170. indices.push((firstIndex + 1));
  37171. indices.push((firstIndex + totalYRotationSteps + 2));
  37172. }
  37173. }
  37174. }
  37175. // Sides
  37176. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37177. // Result
  37178. var vertexData = new VertexData();
  37179. vertexData.indices = indices;
  37180. vertexData.positions = positions;
  37181. vertexData.normals = normals;
  37182. vertexData.uvs = uvs;
  37183. return vertexData;
  37184. };
  37185. /**
  37186. * Creates the VertexData for a cylinder, cone or prism
  37187. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37188. * * height sets the height (y direction) of the cylinder, optional, default 2
  37189. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37190. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37191. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37192. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37193. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37194. * * 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
  37195. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37196. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37197. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37198. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37199. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37200. * * 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)
  37201. * * 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)
  37202. * @returns the VertexData of the cylinder, cone or prism
  37203. */
  37204. VertexData.CreateCylinder = function (options) {
  37205. var height = options.height || 2;
  37206. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37207. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37208. var tessellation = options.tessellation || 24;
  37209. var subdivisions = options.subdivisions || 1;
  37210. var hasRings = options.hasRings ? true : false;
  37211. var enclose = options.enclose ? true : false;
  37212. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37213. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37214. var faceUV = options.faceUV || new Array(3);
  37215. var faceColors = options.faceColors;
  37216. // default face colors and UV if undefined
  37217. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37218. var ringNb = (hasRings) ? subdivisions : 1;
  37219. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37220. var f;
  37221. for (f = 0; f < surfaceNb; f++) {
  37222. if (faceColors && faceColors[f] === undefined) {
  37223. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37224. }
  37225. }
  37226. for (f = 0; f < surfaceNb; f++) {
  37227. if (faceUV && faceUV[f] === undefined) {
  37228. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37229. }
  37230. }
  37231. var indices = new Array();
  37232. var positions = new Array();
  37233. var normals = new Array();
  37234. var uvs = new Array();
  37235. var colors = new Array();
  37236. var angle_step = Math.PI * 2 * arc / tessellation;
  37237. var angle;
  37238. var h;
  37239. var radius;
  37240. var tan = (diameterBottom - diameterTop) / 2 / height;
  37241. var ringVertex = BABYLON.Vector3.Zero();
  37242. var ringNormal = BABYLON.Vector3.Zero();
  37243. var ringFirstVertex = BABYLON.Vector3.Zero();
  37244. var ringFirstNormal = BABYLON.Vector3.Zero();
  37245. var quadNormal = BABYLON.Vector3.Zero();
  37246. var Y = BABYLON.Axis.Y;
  37247. // positions, normals, uvs
  37248. var i;
  37249. var j;
  37250. var r;
  37251. var ringIdx = 1;
  37252. var s = 1; // surface index
  37253. var cs = 0;
  37254. var v = 0;
  37255. for (i = 0; i <= subdivisions; i++) {
  37256. h = i / subdivisions;
  37257. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37258. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37259. for (r = 0; r < ringIdx; r++) {
  37260. if (hasRings) {
  37261. s += r;
  37262. }
  37263. if (enclose) {
  37264. s += 2 * r;
  37265. }
  37266. for (j = 0; j <= tessellation; j++) {
  37267. angle = j * angle_step;
  37268. // position
  37269. ringVertex.x = Math.cos(-angle) * radius;
  37270. ringVertex.y = -height / 2 + h * height;
  37271. ringVertex.z = Math.sin(-angle) * radius;
  37272. // normal
  37273. if (diameterTop === 0 && i === subdivisions) {
  37274. // if no top cap, reuse former normals
  37275. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37276. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37277. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37278. }
  37279. else {
  37280. ringNormal.x = ringVertex.x;
  37281. ringNormal.z = ringVertex.z;
  37282. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37283. ringNormal.normalize();
  37284. }
  37285. // keep first ring vertex values for enclose
  37286. if (j === 0) {
  37287. ringFirstVertex.copyFrom(ringVertex);
  37288. ringFirstNormal.copyFrom(ringNormal);
  37289. }
  37290. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37291. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37292. if (hasRings) {
  37293. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37294. }
  37295. else {
  37296. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37297. }
  37298. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37299. if (faceColors) {
  37300. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37301. }
  37302. }
  37303. // if enclose, add four vertices and their dedicated normals
  37304. if (arc !== 1 && enclose) {
  37305. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37306. positions.push(0, ringVertex.y, 0);
  37307. positions.push(0, ringVertex.y, 0);
  37308. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37309. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37310. quadNormal.normalize();
  37311. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37312. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37313. quadNormal.normalize();
  37314. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37315. if (hasRings) {
  37316. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37317. }
  37318. else {
  37319. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37320. }
  37321. uvs.push(faceUV[s + 1].x, v);
  37322. uvs.push(faceUV[s + 1].z, v);
  37323. if (hasRings) {
  37324. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37325. }
  37326. else {
  37327. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37328. }
  37329. uvs.push(faceUV[s + 2].x, v);
  37330. uvs.push(faceUV[s + 2].z, v);
  37331. if (faceColors) {
  37332. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37333. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37334. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37335. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37336. }
  37337. }
  37338. if (cs !== s) {
  37339. cs = s;
  37340. }
  37341. }
  37342. }
  37343. // indices
  37344. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37345. var s;
  37346. i = 0;
  37347. for (s = 0; s < subdivisions; s++) {
  37348. var i0 = 0;
  37349. var i1 = 0;
  37350. var i2 = 0;
  37351. var i3 = 0;
  37352. for (j = 0; j < tessellation; j++) {
  37353. i0 = i * (e + 1) + j;
  37354. i1 = (i + 1) * (e + 1) + j;
  37355. i2 = i * (e + 1) + (j + 1);
  37356. i3 = (i + 1) * (e + 1) + (j + 1);
  37357. indices.push(i0, i1, i2);
  37358. indices.push(i3, i2, i1);
  37359. }
  37360. if (arc !== 1 && enclose) { // if enclose, add two quads
  37361. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37362. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37363. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37364. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37365. }
  37366. i = (hasRings) ? (i + 2) : (i + 1);
  37367. }
  37368. // Caps
  37369. var createCylinderCap = function (isTop) {
  37370. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37371. if (radius === 0) {
  37372. return;
  37373. }
  37374. // Cap positions, normals & uvs
  37375. var angle;
  37376. var circleVector;
  37377. var i;
  37378. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37379. var c = null;
  37380. if (faceColors) {
  37381. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37382. }
  37383. // cap center
  37384. var vbase = positions.length / 3;
  37385. var offset = isTop ? height / 2 : -height / 2;
  37386. var center = new BABYLON.Vector3(0, offset, 0);
  37387. positions.push(center.x, center.y, center.z);
  37388. normals.push(0, isTop ? 1 : -1, 0);
  37389. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37390. if (c) {
  37391. colors.push(c.r, c.g, c.b, c.a);
  37392. }
  37393. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37394. for (i = 0; i <= tessellation; i++) {
  37395. angle = Math.PI * 2 * i * arc / tessellation;
  37396. var cos = Math.cos(-angle);
  37397. var sin = Math.sin(-angle);
  37398. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37399. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37400. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37401. normals.push(0, isTop ? 1 : -1, 0);
  37402. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37403. if (c) {
  37404. colors.push(c.r, c.g, c.b, c.a);
  37405. }
  37406. }
  37407. // Cap indices
  37408. for (i = 0; i < tessellation; i++) {
  37409. if (!isTop) {
  37410. indices.push(vbase);
  37411. indices.push(vbase + (i + 1));
  37412. indices.push(vbase + (i + 2));
  37413. }
  37414. else {
  37415. indices.push(vbase);
  37416. indices.push(vbase + (i + 2));
  37417. indices.push(vbase + (i + 1));
  37418. }
  37419. }
  37420. };
  37421. // add caps to geometry
  37422. createCylinderCap(false);
  37423. createCylinderCap(true);
  37424. // Sides
  37425. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37426. var vertexData = new VertexData();
  37427. vertexData.indices = indices;
  37428. vertexData.positions = positions;
  37429. vertexData.normals = normals;
  37430. vertexData.uvs = uvs;
  37431. if (faceColors) {
  37432. vertexData.colors = colors;
  37433. }
  37434. return vertexData;
  37435. };
  37436. /**
  37437. * Creates the VertexData for a torus
  37438. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37439. * * diameter the diameter of the torus, optional default 1
  37440. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37441. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37442. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37443. * * 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)
  37444. * * 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)
  37445. * @returns the VertexData of the torus
  37446. */
  37447. VertexData.CreateTorus = function (options) {
  37448. var indices = [];
  37449. var positions = [];
  37450. var normals = [];
  37451. var uvs = [];
  37452. var diameter = options.diameter || 1;
  37453. var thickness = options.thickness || 0.5;
  37454. var tessellation = options.tessellation || 16;
  37455. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37456. var stride = tessellation + 1;
  37457. for (var i = 0; i <= tessellation; i++) {
  37458. var u = i / tessellation;
  37459. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37460. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37461. for (var j = 0; j <= tessellation; j++) {
  37462. var v = 1 - j / tessellation;
  37463. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37464. var dx = Math.cos(innerAngle);
  37465. var dy = Math.sin(innerAngle);
  37466. // Create a vertex.
  37467. var normal = new BABYLON.Vector3(dx, dy, 0);
  37468. var position = normal.scale(thickness / 2);
  37469. var textureCoordinate = new BABYLON.Vector2(u, v);
  37470. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37471. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37472. positions.push(position.x, position.y, position.z);
  37473. normals.push(normal.x, normal.y, normal.z);
  37474. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37475. // And create indices for two triangles.
  37476. var nextI = (i + 1) % stride;
  37477. var nextJ = (j + 1) % stride;
  37478. indices.push(i * stride + j);
  37479. indices.push(i * stride + nextJ);
  37480. indices.push(nextI * stride + j);
  37481. indices.push(i * stride + nextJ);
  37482. indices.push(nextI * stride + nextJ);
  37483. indices.push(nextI * stride + j);
  37484. }
  37485. }
  37486. // Sides
  37487. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37488. // Result
  37489. var vertexData = new VertexData();
  37490. vertexData.indices = indices;
  37491. vertexData.positions = positions;
  37492. vertexData.normals = normals;
  37493. vertexData.uvs = uvs;
  37494. return vertexData;
  37495. };
  37496. /**
  37497. * Creates the VertexData of the LineSystem
  37498. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37499. * - lines an array of lines, each line being an array of successive Vector3
  37500. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37501. * @returns the VertexData of the LineSystem
  37502. */
  37503. VertexData.CreateLineSystem = function (options) {
  37504. var indices = [];
  37505. var positions = [];
  37506. var lines = options.lines;
  37507. var colors = options.colors;
  37508. var vertexColors = [];
  37509. var idx = 0;
  37510. for (var l = 0; l < lines.length; l++) {
  37511. var points = lines[l];
  37512. for (var index = 0; index < points.length; index++) {
  37513. positions.push(points[index].x, points[index].y, points[index].z);
  37514. if (colors) {
  37515. var color = colors[l];
  37516. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37517. }
  37518. if (index > 0) {
  37519. indices.push(idx - 1);
  37520. indices.push(idx);
  37521. }
  37522. idx++;
  37523. }
  37524. }
  37525. var vertexData = new VertexData();
  37526. vertexData.indices = indices;
  37527. vertexData.positions = positions;
  37528. if (colors) {
  37529. vertexData.colors = vertexColors;
  37530. }
  37531. return vertexData;
  37532. };
  37533. /**
  37534. * Create the VertexData for a DashedLines
  37535. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37536. * - points an array successive Vector3
  37537. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37538. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37539. * - dashNb the intended total number of dashes, optional, default 200
  37540. * @returns the VertexData for the DashedLines
  37541. */
  37542. VertexData.CreateDashedLines = function (options) {
  37543. var dashSize = options.dashSize || 3;
  37544. var gapSize = options.gapSize || 1;
  37545. var dashNb = options.dashNb || 200;
  37546. var points = options.points;
  37547. var positions = new Array();
  37548. var indices = new Array();
  37549. var curvect = BABYLON.Vector3.Zero();
  37550. var lg = 0;
  37551. var nb = 0;
  37552. var shft = 0;
  37553. var dashshft = 0;
  37554. var curshft = 0;
  37555. var idx = 0;
  37556. var i = 0;
  37557. for (i = 0; i < points.length - 1; i++) {
  37558. points[i + 1].subtractToRef(points[i], curvect);
  37559. lg += curvect.length();
  37560. }
  37561. shft = lg / dashNb;
  37562. dashshft = dashSize * shft / (dashSize + gapSize);
  37563. for (i = 0; i < points.length - 1; i++) {
  37564. points[i + 1].subtractToRef(points[i], curvect);
  37565. nb = Math.floor(curvect.length() / shft);
  37566. curvect.normalize();
  37567. for (var j = 0; j < nb; j++) {
  37568. curshft = shft * j;
  37569. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37570. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37571. indices.push(idx, idx + 1);
  37572. idx += 2;
  37573. }
  37574. }
  37575. // Result
  37576. var vertexData = new VertexData();
  37577. vertexData.positions = positions;
  37578. vertexData.indices = indices;
  37579. return vertexData;
  37580. };
  37581. /**
  37582. * Creates the VertexData for a Ground
  37583. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37584. * - width the width (x direction) of the ground, optional, default 1
  37585. * - height the height (z direction) of the ground, optional, default 1
  37586. * - subdivisions the number of subdivisions per side, optional, default 1
  37587. * @returns the VertexData of the Ground
  37588. */
  37589. VertexData.CreateGround = function (options) {
  37590. var indices = [];
  37591. var positions = [];
  37592. var normals = [];
  37593. var uvs = [];
  37594. var row, col;
  37595. var width = options.width || 1;
  37596. var height = options.height || 1;
  37597. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37598. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37599. for (row = 0; row <= subdivisionsY; row++) {
  37600. for (col = 0; col <= subdivisionsX; col++) {
  37601. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37602. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37603. positions.push(position.x, position.y, position.z);
  37604. normals.push(normal.x, normal.y, normal.z);
  37605. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37606. }
  37607. }
  37608. for (row = 0; row < subdivisionsY; row++) {
  37609. for (col = 0; col < subdivisionsX; col++) {
  37610. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37611. indices.push(col + 1 + row * (subdivisionsX + 1));
  37612. indices.push(col + row * (subdivisionsX + 1));
  37613. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37614. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37615. indices.push(col + row * (subdivisionsX + 1));
  37616. }
  37617. }
  37618. // Result
  37619. var vertexData = new VertexData();
  37620. vertexData.indices = indices;
  37621. vertexData.positions = positions;
  37622. vertexData.normals = normals;
  37623. vertexData.uvs = uvs;
  37624. return vertexData;
  37625. };
  37626. /**
  37627. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37628. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37629. * * xmin the ground minimum X coordinate, optional, default -1
  37630. * * zmin the ground minimum Z coordinate, optional, default -1
  37631. * * xmax the ground maximum X coordinate, optional, default 1
  37632. * * zmax the ground maximum Z coordinate, optional, default 1
  37633. * * 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}
  37634. * * 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}
  37635. * @returns the VertexData of the TiledGround
  37636. */
  37637. VertexData.CreateTiledGround = function (options) {
  37638. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37639. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37640. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37641. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37642. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37643. var precision = options.precision || { w: 1, h: 1 };
  37644. var indices = new Array();
  37645. var positions = new Array();
  37646. var normals = new Array();
  37647. var uvs = new Array();
  37648. var row, col, tileRow, tileCol;
  37649. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37650. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37651. precision.w = (precision.w < 1) ? 1 : precision.w;
  37652. precision.h = (precision.h < 1) ? 1 : precision.h;
  37653. var tileSize = {
  37654. 'w': (xmax - xmin) / subdivisions.w,
  37655. 'h': (zmax - zmin) / subdivisions.h
  37656. };
  37657. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37658. // Indices
  37659. var base = positions.length / 3;
  37660. var rowLength = precision.w + 1;
  37661. for (row = 0; row < precision.h; row++) {
  37662. for (col = 0; col < precision.w; col++) {
  37663. var square = [
  37664. base + col + row * rowLength,
  37665. base + (col + 1) + row * rowLength,
  37666. base + (col + 1) + (row + 1) * rowLength,
  37667. base + col + (row + 1) * rowLength
  37668. ];
  37669. indices.push(square[1]);
  37670. indices.push(square[2]);
  37671. indices.push(square[3]);
  37672. indices.push(square[0]);
  37673. indices.push(square[1]);
  37674. indices.push(square[3]);
  37675. }
  37676. }
  37677. // Position, normals and uvs
  37678. var position = BABYLON.Vector3.Zero();
  37679. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37680. for (row = 0; row <= precision.h; row++) {
  37681. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37682. for (col = 0; col <= precision.w; col++) {
  37683. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37684. position.y = 0;
  37685. positions.push(position.x, position.y, position.z);
  37686. normals.push(normal.x, normal.y, normal.z);
  37687. uvs.push(col / precision.w, row / precision.h);
  37688. }
  37689. }
  37690. }
  37691. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37692. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37693. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37694. }
  37695. }
  37696. // Result
  37697. var vertexData = new VertexData();
  37698. vertexData.indices = indices;
  37699. vertexData.positions = positions;
  37700. vertexData.normals = normals;
  37701. vertexData.uvs = uvs;
  37702. return vertexData;
  37703. };
  37704. /**
  37705. * Creates the VertexData of the Ground designed from a heightmap
  37706. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37707. * * width the width (x direction) of the ground
  37708. * * height the height (z direction) of the ground
  37709. * * subdivisions the number of subdivisions per side
  37710. * * minHeight the minimum altitude on the ground, optional, default 0
  37711. * * maxHeight the maximum altitude on the ground, optional default 1
  37712. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37713. * * buffer the array holding the image color data
  37714. * * bufferWidth the width of image
  37715. * * bufferHeight the height of image
  37716. * @returns the VertexData of the Ground designed from a heightmap
  37717. */
  37718. VertexData.CreateGroundFromHeightMap = function (options) {
  37719. var indices = [];
  37720. var positions = [];
  37721. var normals = [];
  37722. var uvs = [];
  37723. var row, col;
  37724. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37725. // Vertices
  37726. for (row = 0; row <= options.subdivisions; row++) {
  37727. for (col = 0; col <= options.subdivisions; col++) {
  37728. 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));
  37729. // Compute height
  37730. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37731. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37732. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37733. var r = options.buffer[pos] / 255.0;
  37734. var g = options.buffer[pos + 1] / 255.0;
  37735. var b = options.buffer[pos + 2] / 255.0;
  37736. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37737. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37738. // Add vertex
  37739. positions.push(position.x, position.y, position.z);
  37740. normals.push(0, 0, 0);
  37741. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37742. }
  37743. }
  37744. // Indices
  37745. for (row = 0; row < options.subdivisions; row++) {
  37746. for (col = 0; col < options.subdivisions; col++) {
  37747. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37748. indices.push(col + 1 + row * (options.subdivisions + 1));
  37749. indices.push(col + row * (options.subdivisions + 1));
  37750. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37751. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37752. indices.push(col + row * (options.subdivisions + 1));
  37753. }
  37754. }
  37755. // Normals
  37756. VertexData.ComputeNormals(positions, indices, normals);
  37757. // Result
  37758. var vertexData = new VertexData();
  37759. vertexData.indices = indices;
  37760. vertexData.positions = positions;
  37761. vertexData.normals = normals;
  37762. vertexData.uvs = uvs;
  37763. return vertexData;
  37764. };
  37765. /**
  37766. * Creates the VertexData for a Plane
  37767. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37768. * * size sets the width and height of the plane to the value of size, optional default 1
  37769. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37770. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37771. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37772. * * 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)
  37773. * * 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)
  37774. * @returns the VertexData of the box
  37775. */
  37776. VertexData.CreatePlane = function (options) {
  37777. var indices = [];
  37778. var positions = [];
  37779. var normals = [];
  37780. var uvs = [];
  37781. var width = options.width || options.size || 1;
  37782. var height = options.height || options.size || 1;
  37783. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37784. // Vertices
  37785. var halfWidth = width / 2.0;
  37786. var halfHeight = height / 2.0;
  37787. positions.push(-halfWidth, -halfHeight, 0);
  37788. normals.push(0, 0, -1.0);
  37789. uvs.push(0.0, 0.0);
  37790. positions.push(halfWidth, -halfHeight, 0);
  37791. normals.push(0, 0, -1.0);
  37792. uvs.push(1.0, 0.0);
  37793. positions.push(halfWidth, halfHeight, 0);
  37794. normals.push(0, 0, -1.0);
  37795. uvs.push(1.0, 1.0);
  37796. positions.push(-halfWidth, halfHeight, 0);
  37797. normals.push(0, 0, -1.0);
  37798. uvs.push(0.0, 1.0);
  37799. // Indices
  37800. indices.push(0);
  37801. indices.push(1);
  37802. indices.push(2);
  37803. indices.push(0);
  37804. indices.push(2);
  37805. indices.push(3);
  37806. // Sides
  37807. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37808. // Result
  37809. var vertexData = new VertexData();
  37810. vertexData.indices = indices;
  37811. vertexData.positions = positions;
  37812. vertexData.normals = normals;
  37813. vertexData.uvs = uvs;
  37814. return vertexData;
  37815. };
  37816. /**
  37817. * Creates the VertexData of the Disc or regular Polygon
  37818. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37819. * * radius the radius of the disc, optional default 0.5
  37820. * * tessellation the number of polygon sides, optional, default 64
  37821. * * 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
  37822. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37823. * * 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)
  37824. * * 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)
  37825. * @returns the VertexData of the box
  37826. */
  37827. VertexData.CreateDisc = function (options) {
  37828. var positions = new Array();
  37829. var indices = new Array();
  37830. var normals = new Array();
  37831. var uvs = new Array();
  37832. var radius = options.radius || 0.5;
  37833. var tessellation = options.tessellation || 64;
  37834. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37835. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37836. // positions and uvs
  37837. positions.push(0, 0, 0); // disc center first
  37838. uvs.push(0.5, 0.5);
  37839. var theta = Math.PI * 2 * arc;
  37840. var step = theta / tessellation;
  37841. for (var a = 0; a < theta; a += step) {
  37842. var x = Math.cos(a);
  37843. var y = Math.sin(a);
  37844. var u = (x + 1) / 2;
  37845. var v = (1 - y) / 2;
  37846. positions.push(radius * x, radius * y, 0);
  37847. uvs.push(u, v);
  37848. }
  37849. if (arc === 1) {
  37850. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37851. uvs.push(uvs[2], uvs[3]);
  37852. }
  37853. //indices
  37854. var vertexNb = positions.length / 3;
  37855. for (var i = 1; i < vertexNb - 1; i++) {
  37856. indices.push(i + 1, 0, i);
  37857. }
  37858. // result
  37859. VertexData.ComputeNormals(positions, indices, normals);
  37860. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37861. var vertexData = new VertexData();
  37862. vertexData.indices = indices;
  37863. vertexData.positions = positions;
  37864. vertexData.normals = normals;
  37865. vertexData.uvs = uvs;
  37866. return vertexData;
  37867. };
  37868. /**
  37869. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37870. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37871. * @param polygon a mesh built from polygonTriangulation.build()
  37872. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37873. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37874. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37875. * @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)
  37876. * @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)
  37877. * @returns the VertexData of the Polygon
  37878. */
  37879. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37880. var faceUV = fUV || new Array(3);
  37881. var faceColors = fColors;
  37882. var colors = [];
  37883. // default face colors and UV if undefined
  37884. for (var f = 0; f < 3; f++) {
  37885. if (faceUV[f] === undefined) {
  37886. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37887. }
  37888. if (faceColors && faceColors[f] === undefined) {
  37889. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37890. }
  37891. }
  37892. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37893. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37894. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37895. var indices = polygon.getIndices();
  37896. // set face colours and textures
  37897. var idx = 0;
  37898. var face = 0;
  37899. for (var index = 0; index < normals.length; index += 3) {
  37900. //Edge Face no. 1
  37901. if (Math.abs(normals[index + 1]) < 0.001) {
  37902. face = 1;
  37903. }
  37904. //Top Face no. 0
  37905. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37906. face = 0;
  37907. }
  37908. //Bottom Face no. 2
  37909. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37910. face = 2;
  37911. }
  37912. idx = index / 3;
  37913. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37914. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37915. if (faceColors) {
  37916. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37917. }
  37918. }
  37919. // sides
  37920. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37921. // Result
  37922. var vertexData = new VertexData();
  37923. vertexData.indices = indices;
  37924. vertexData.positions = positions;
  37925. vertexData.normals = normals;
  37926. vertexData.uvs = uvs;
  37927. if (faceColors) {
  37928. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37929. vertexData.colors = totalColors;
  37930. }
  37931. return vertexData;
  37932. };
  37933. /**
  37934. * Creates the VertexData of the IcoSphere
  37935. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37936. * * radius the radius of the IcoSphere, optional default 1
  37937. * * radiusX allows stretching in the x direction, optional, default radius
  37938. * * radiusY allows stretching in the y direction, optional, default radius
  37939. * * radiusZ allows stretching in the z direction, optional, default radius
  37940. * * flat when true creates a flat shaded mesh, optional, default true
  37941. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37942. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37943. * * 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)
  37944. * * 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)
  37945. * @returns the VertexData of the IcoSphere
  37946. */
  37947. VertexData.CreateIcoSphere = function (options) {
  37948. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37949. var radius = options.radius || 1;
  37950. var flat = (options.flat === undefined) ? true : options.flat;
  37951. var subdivisions = options.subdivisions || 4;
  37952. var radiusX = options.radiusX || radius;
  37953. var radiusY = options.radiusY || radius;
  37954. var radiusZ = options.radiusZ || radius;
  37955. var t = (1 + Math.sqrt(5)) / 2;
  37956. // 12 vertex x,y,z
  37957. var ico_vertices = [
  37958. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37959. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37960. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37961. ];
  37962. // index of 3 vertex makes a face of icopshere
  37963. var ico_indices = [
  37964. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37965. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37966. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37967. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37968. ];
  37969. // vertex for uv have aliased position, not for UV
  37970. var vertices_unalias_id = [
  37971. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37972. // vertex alias
  37973. 0,
  37974. 2,
  37975. 3,
  37976. 3,
  37977. 3,
  37978. 4,
  37979. 7,
  37980. 8,
  37981. 9,
  37982. 9,
  37983. 10,
  37984. 11 // 23: B + 12
  37985. ];
  37986. // uv as integer step (not pixels !)
  37987. var ico_vertexuv = [
  37988. 5, 1, 3, 1, 6, 4, 0, 0,
  37989. 5, 3, 4, 2, 2, 2, 4, 0,
  37990. 2, 0, 1, 1, 6, 0, 6, 2,
  37991. // vertex alias (for same vertex on different faces)
  37992. 0, 4,
  37993. 3, 3,
  37994. 4, 4,
  37995. 3, 1,
  37996. 4, 2,
  37997. 4, 4,
  37998. 0, 2,
  37999. 1, 1,
  38000. 2, 2,
  38001. 3, 3,
  38002. 1, 3,
  38003. 2, 4 // 23: B + 12
  38004. ];
  38005. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38006. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38007. // First island of uv mapping
  38008. // v = 4h 3+ 2
  38009. // v = 3h 9+ 4
  38010. // v = 2h 9+ 5 B
  38011. // v = 1h 9 1 0
  38012. // v = 0h 3 8 7 A
  38013. // u = 0 1 2 3 4 5 6 *a
  38014. // Second island of uv mapping
  38015. // v = 4h 0+ B+ 4+
  38016. // v = 3h A+ 2+
  38017. // v = 2h 7+ 6 3+
  38018. // v = 1h 8+ 3+
  38019. // v = 0h
  38020. // u = 0 1 2 3 4 5 6 *a
  38021. // Face layout on texture UV mapping
  38022. // ============
  38023. // \ 4 /\ 16 / ======
  38024. // \ / \ / /\ 11 /
  38025. // \/ 7 \/ / \ /
  38026. // ======= / 10 \/
  38027. // /\ 17 /\ =======
  38028. // / \ / \ \ 15 /\
  38029. // / 8 \/ 12 \ \ / \
  38030. // ============ \/ 6 \
  38031. // \ 18 /\ ============
  38032. // \ / \ \ 5 /\ 0 /
  38033. // \/ 13 \ \ / \ /
  38034. // ======= \/ 1 \/
  38035. // =============
  38036. // /\ 19 /\ 2 /\
  38037. // / \ / \ / \
  38038. // / 14 \/ 9 \/ 3 \
  38039. // ===================
  38040. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38041. var ustep = 138 / 1024;
  38042. var vstep = 239 / 1024;
  38043. var uoffset = 60 / 1024;
  38044. var voffset = 26 / 1024;
  38045. // Second island should have margin, not to touch the first island
  38046. // avoid any borderline artefact in pixel rounding
  38047. var island_u_offset = -40 / 1024;
  38048. var island_v_offset = +20 / 1024;
  38049. // face is either island 0 or 1 :
  38050. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38051. var island = [
  38052. 0, 0, 0, 0, 1,
  38053. 0, 0, 1, 1, 0,
  38054. 0, 0, 1, 1, 0,
  38055. 0, 1, 1, 1, 0 // 15 - 19
  38056. ];
  38057. var indices = new Array();
  38058. var positions = new Array();
  38059. var normals = new Array();
  38060. var uvs = new Array();
  38061. var current_indice = 0;
  38062. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38063. var face_vertex_pos = new Array(3);
  38064. var face_vertex_uv = new Array(3);
  38065. var v012;
  38066. for (v012 = 0; v012 < 3; v012++) {
  38067. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38068. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38069. }
  38070. // create all with normals
  38071. for (var face = 0; face < 20; face++) {
  38072. // 3 vertex per face
  38073. for (v012 = 0; v012 < 3; v012++) {
  38074. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38075. var v_id = ico_indices[3 * face + v012];
  38076. // vertex have 3D position (x,y,z)
  38077. 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]);
  38078. // Normalize to get normal, then scale to radius
  38079. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38080. // uv Coordinates from vertex ID
  38081. 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);
  38082. }
  38083. // Subdivide the face (interpolate pos, norm, uv)
  38084. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38085. // - norm is linear interpolation of vertex corner normal
  38086. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38087. // - uv is linear interpolation
  38088. //
  38089. // Topology is as below for sub-divide by 2
  38090. // vertex shown as v0,v1,v2
  38091. // interp index is i1 to progress in range [v0,v1[
  38092. // interp index is i2 to progress in range [v0,v2[
  38093. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38094. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38095. //
  38096. //
  38097. // i2 v2
  38098. // ^ ^
  38099. // / / \
  38100. // / / \
  38101. // / / \
  38102. // / / (0,1) \
  38103. // / #---------\
  38104. // / / \ (0,0)'/ \
  38105. // / / \ / \
  38106. // / / \ / \
  38107. // / / (0,0) \ / (1,0) \
  38108. // / #---------#---------\
  38109. // v0 v1
  38110. //
  38111. // --------------------> i1
  38112. //
  38113. // interp of (i1,i2):
  38114. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38115. // along i1 : lerp(x0,x1, i1/(S-i2))
  38116. //
  38117. // centroid of triangle is needed to get help normal computation
  38118. // (c1,c2) are used for centroid location
  38119. var interp_vertex = function (i1, i2, c1, c2) {
  38120. // vertex is interpolated from
  38121. // - face_vertex_pos[0..2]
  38122. // - face_vertex_uv[0..2]
  38123. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38124. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38125. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38126. pos_interp.normalize();
  38127. var vertex_normal;
  38128. if (flat) {
  38129. // in flat mode, recalculate normal as face centroid normal
  38130. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38131. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38132. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38133. }
  38134. else {
  38135. // in smooth mode, recalculate normal from each single vertex position
  38136. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38137. }
  38138. // Vertex normal need correction due to X,Y,Z radius scaling
  38139. vertex_normal.x /= radiusX;
  38140. vertex_normal.y /= radiusY;
  38141. vertex_normal.z /= radiusZ;
  38142. vertex_normal.normalize();
  38143. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38144. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38145. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38146. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38147. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38148. uvs.push(uv_interp.x, uv_interp.y);
  38149. // push each vertex has member of a face
  38150. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38151. indices.push(current_indice);
  38152. current_indice++;
  38153. };
  38154. for (var i2 = 0; i2 < subdivisions; i2++) {
  38155. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38156. // face : (i1,i2) for /\ :
  38157. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38158. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38159. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38160. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38161. if (i1 + i2 + 1 < subdivisions) {
  38162. // face : (i1,i2)' for \/ :
  38163. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38164. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38165. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38166. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38167. }
  38168. }
  38169. }
  38170. }
  38171. // Sides
  38172. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38173. // Result
  38174. var vertexData = new VertexData();
  38175. vertexData.indices = indices;
  38176. vertexData.positions = positions;
  38177. vertexData.normals = normals;
  38178. vertexData.uvs = uvs;
  38179. return vertexData;
  38180. };
  38181. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38182. /**
  38183. * Creates the VertexData for a Polyhedron
  38184. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38185. * * type provided types are:
  38186. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38187. * * 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)
  38188. * * size the size of the IcoSphere, optional default 1
  38189. * * sizeX allows stretching in the x direction, optional, default size
  38190. * * sizeY allows stretching in the y direction, optional, default size
  38191. * * sizeZ allows stretching in the z direction, optional, default size
  38192. * * 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
  38193. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38194. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38195. * * flat when true creates a flat shaded mesh, optional, default true
  38196. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38197. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38198. * * 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)
  38199. * * 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)
  38200. * @returns the VertexData of the Polyhedron
  38201. */
  38202. VertexData.CreatePolyhedron = function (options) {
  38203. // provided polyhedron types :
  38204. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38205. // 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)
  38206. var polyhedra = [];
  38207. 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]] };
  38208. 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]] };
  38209. polyhedra[2] = {
  38210. 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]],
  38211. 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]]
  38212. };
  38213. polyhedra[3] = {
  38214. 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]],
  38215. 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]]
  38216. };
  38217. polyhedra[4] = {
  38218. 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]],
  38219. 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]]
  38220. };
  38221. 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]] };
  38222. 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]] };
  38223. 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]] };
  38224. 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]] };
  38225. 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]] };
  38226. 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]] };
  38227. 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]] };
  38228. 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]] };
  38229. 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]] };
  38230. polyhedra[14] = {
  38231. 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]],
  38232. 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]]
  38233. };
  38234. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38235. var size = options.size;
  38236. var sizeX = options.sizeX || size || 1;
  38237. var sizeY = options.sizeY || size || 1;
  38238. var sizeZ = options.sizeZ || size || 1;
  38239. var data = options.custom || polyhedra[type];
  38240. var nbfaces = data.face.length;
  38241. var faceUV = options.faceUV || new Array(nbfaces);
  38242. var faceColors = options.faceColors;
  38243. var flat = (options.flat === undefined) ? true : options.flat;
  38244. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38245. var positions = new Array();
  38246. var indices = new Array();
  38247. var normals = new Array();
  38248. var uvs = new Array();
  38249. var colors = new Array();
  38250. var index = 0;
  38251. var faceIdx = 0; // face cursor in the array "indexes"
  38252. var indexes = new Array();
  38253. var i = 0;
  38254. var f = 0;
  38255. var u, v, ang, x, y, tmp;
  38256. // default face colors and UV if undefined
  38257. if (flat) {
  38258. for (f = 0; f < nbfaces; f++) {
  38259. if (faceColors && faceColors[f] === undefined) {
  38260. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38261. }
  38262. if (faceUV && faceUV[f] === undefined) {
  38263. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38264. }
  38265. }
  38266. }
  38267. if (!flat) {
  38268. for (i = 0; i < data.vertex.length; i++) {
  38269. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38270. uvs.push(0, 0);
  38271. }
  38272. for (f = 0; f < nbfaces; f++) {
  38273. for (i = 0; i < data.face[f].length - 2; i++) {
  38274. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38275. }
  38276. }
  38277. }
  38278. else {
  38279. for (f = 0; f < nbfaces; f++) {
  38280. var fl = data.face[f].length; // number of vertices of the current face
  38281. ang = 2 * Math.PI / fl;
  38282. x = 0.5 * Math.tan(ang / 2);
  38283. y = 0.5;
  38284. // positions, uvs, colors
  38285. for (i = 0; i < fl; i++) {
  38286. // positions
  38287. 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);
  38288. indexes.push(index);
  38289. index++;
  38290. // uvs
  38291. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38292. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38293. uvs.push(u, v);
  38294. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38295. y = x * Math.sin(ang) + y * Math.cos(ang);
  38296. x = tmp;
  38297. // colors
  38298. if (faceColors) {
  38299. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38300. }
  38301. }
  38302. // indices from indexes
  38303. for (i = 0; i < fl - 2; i++) {
  38304. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38305. }
  38306. faceIdx += fl;
  38307. }
  38308. }
  38309. VertexData.ComputeNormals(positions, indices, normals);
  38310. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38311. var vertexData = new VertexData();
  38312. vertexData.positions = positions;
  38313. vertexData.indices = indices;
  38314. vertexData.normals = normals;
  38315. vertexData.uvs = uvs;
  38316. if (faceColors && flat) {
  38317. vertexData.colors = colors;
  38318. }
  38319. return vertexData;
  38320. };
  38321. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38322. /**
  38323. * Creates the VertexData for a TorusKnot
  38324. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38325. * * radius the radius of the torus knot, optional, default 2
  38326. * * tube the thickness of the tube, optional, default 0.5
  38327. * * radialSegments the number of sides on each tube segments, optional, default 32
  38328. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38329. * * p the number of windings around the z axis, optional, default 2
  38330. * * q the number of windings around the x axis, optional, default 3
  38331. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38332. * * 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)
  38333. * * 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)
  38334. * @returns the VertexData of the Torus Knot
  38335. */
  38336. VertexData.CreateTorusKnot = function (options) {
  38337. var indices = new Array();
  38338. var positions = new Array();
  38339. var normals = new Array();
  38340. var uvs = new Array();
  38341. var radius = options.radius || 2;
  38342. var tube = options.tube || 0.5;
  38343. var radialSegments = options.radialSegments || 32;
  38344. var tubularSegments = options.tubularSegments || 32;
  38345. var p = options.p || 2;
  38346. var q = options.q || 3;
  38347. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38348. // Helper
  38349. var getPos = function (angle) {
  38350. var cu = Math.cos(angle);
  38351. var su = Math.sin(angle);
  38352. var quOverP = q / p * angle;
  38353. var cs = Math.cos(quOverP);
  38354. var tx = radius * (2 + cs) * 0.5 * cu;
  38355. var ty = radius * (2 + cs) * su * 0.5;
  38356. var tz = radius * Math.sin(quOverP) * 0.5;
  38357. return new BABYLON.Vector3(tx, ty, tz);
  38358. };
  38359. // Vertices
  38360. var i;
  38361. var j;
  38362. for (i = 0; i <= radialSegments; i++) {
  38363. var modI = i % radialSegments;
  38364. var u = modI / radialSegments * 2 * p * Math.PI;
  38365. var p1 = getPos(u);
  38366. var p2 = getPos(u + 0.01);
  38367. var tang = p2.subtract(p1);
  38368. var n = p2.add(p1);
  38369. var bitan = BABYLON.Vector3.Cross(tang, n);
  38370. n = BABYLON.Vector3.Cross(bitan, tang);
  38371. bitan.normalize();
  38372. n.normalize();
  38373. for (j = 0; j < tubularSegments; j++) {
  38374. var modJ = j % tubularSegments;
  38375. var v = modJ / tubularSegments * 2 * Math.PI;
  38376. var cx = -tube * Math.cos(v);
  38377. var cy = tube * Math.sin(v);
  38378. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38379. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38380. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38381. uvs.push(i / radialSegments);
  38382. uvs.push(j / tubularSegments);
  38383. }
  38384. }
  38385. for (i = 0; i < radialSegments; i++) {
  38386. for (j = 0; j < tubularSegments; j++) {
  38387. var jNext = (j + 1) % tubularSegments;
  38388. var a = i * tubularSegments + j;
  38389. var b = (i + 1) * tubularSegments + j;
  38390. var c = (i + 1) * tubularSegments + jNext;
  38391. var d = i * tubularSegments + jNext;
  38392. indices.push(d);
  38393. indices.push(b);
  38394. indices.push(a);
  38395. indices.push(d);
  38396. indices.push(c);
  38397. indices.push(b);
  38398. }
  38399. }
  38400. // Normals
  38401. VertexData.ComputeNormals(positions, indices, normals);
  38402. // Sides
  38403. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38404. // Result
  38405. var vertexData = new VertexData();
  38406. vertexData.indices = indices;
  38407. vertexData.positions = positions;
  38408. vertexData.normals = normals;
  38409. vertexData.uvs = uvs;
  38410. return vertexData;
  38411. };
  38412. // Tools
  38413. /**
  38414. * Compute normals for given positions and indices
  38415. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38416. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38417. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38418. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38419. * * facetNormals : optional array of facet normals (vector3)
  38420. * * facetPositions : optional array of facet positions (vector3)
  38421. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38422. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38423. * * bInfo : optional bounding info, required for facetPartitioning computation
  38424. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38425. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38426. * * useRightHandedSystem: optional boolean to for right handed system computation
  38427. * * depthSort : optional boolean to enable the facet depth sort computation
  38428. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38429. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38430. */
  38431. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38432. // temporary scalar variables
  38433. var index = 0; // facet index
  38434. var p1p2x = 0.0; // p1p2 vector x coordinate
  38435. var p1p2y = 0.0; // p1p2 vector y coordinate
  38436. var p1p2z = 0.0; // p1p2 vector z coordinate
  38437. var p3p2x = 0.0; // p3p2 vector x coordinate
  38438. var p3p2y = 0.0; // p3p2 vector y coordinate
  38439. var p3p2z = 0.0; // p3p2 vector z coordinate
  38440. var faceNormalx = 0.0; // facet normal x coordinate
  38441. var faceNormaly = 0.0; // facet normal y coordinate
  38442. var faceNormalz = 0.0; // facet normal z coordinate
  38443. var length = 0.0; // facet normal length before normalization
  38444. var v1x = 0; // vector1 x index in the positions array
  38445. var v1y = 0; // vector1 y index in the positions array
  38446. var v1z = 0; // vector1 z index in the positions array
  38447. var v2x = 0; // vector2 x index in the positions array
  38448. var v2y = 0; // vector2 y index in the positions array
  38449. var v2z = 0; // vector2 z index in the positions array
  38450. var v3x = 0; // vector3 x index in the positions array
  38451. var v3y = 0; // vector3 y index in the positions array
  38452. var v3z = 0; // vector3 z index in the positions array
  38453. var computeFacetNormals = false;
  38454. var computeFacetPositions = false;
  38455. var computeFacetPartitioning = false;
  38456. var computeDepthSort = false;
  38457. var faceNormalSign = 1;
  38458. var ratio = 0;
  38459. var distanceTo = null;
  38460. if (options) {
  38461. computeFacetNormals = (options.facetNormals) ? true : false;
  38462. computeFacetPositions = (options.facetPositions) ? true : false;
  38463. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38464. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38465. ratio = options.ratio || 0;
  38466. computeDepthSort = (options.depthSort) ? true : false;
  38467. distanceTo = (options.distanceTo);
  38468. if (computeDepthSort) {
  38469. if (distanceTo === undefined) {
  38470. distanceTo = BABYLON.Vector3.Zero();
  38471. }
  38472. var depthSortedFacets = options.depthSortedFacets;
  38473. }
  38474. }
  38475. // facetPartitioning reinit if needed
  38476. var xSubRatio = 0;
  38477. var ySubRatio = 0;
  38478. var zSubRatio = 0;
  38479. var subSq = 0;
  38480. if (computeFacetPartitioning && options && options.bbSize) {
  38481. var ox = 0; // X partitioning index for facet position
  38482. var oy = 0; // Y partinioning index for facet position
  38483. var oz = 0; // Z partinioning index for facet position
  38484. var b1x = 0; // X partitioning index for facet v1 vertex
  38485. var b1y = 0; // Y partitioning index for facet v1 vertex
  38486. var b1z = 0; // z partitioning index for facet v1 vertex
  38487. var b2x = 0; // X partitioning index for facet v2 vertex
  38488. var b2y = 0; // Y partitioning index for facet v2 vertex
  38489. var b2z = 0; // Z partitioning index for facet v2 vertex
  38490. var b3x = 0; // X partitioning index for facet v3 vertex
  38491. var b3y = 0; // Y partitioning index for facet v3 vertex
  38492. var b3z = 0; // Z partitioning index for facet v3 vertex
  38493. var block_idx_o = 0; // facet barycenter block index
  38494. var block_idx_v1 = 0; // v1 vertex block index
  38495. var block_idx_v2 = 0; // v2 vertex block index
  38496. var block_idx_v3 = 0; // v3 vertex block index
  38497. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38498. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38499. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38500. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38501. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38502. subSq = options.subDiv.max * options.subDiv.max;
  38503. options.facetPartitioning.length = 0;
  38504. }
  38505. // reset the normals
  38506. for (index = 0; index < positions.length; index++) {
  38507. normals[index] = 0.0;
  38508. }
  38509. // Loop : 1 indice triplet = 1 facet
  38510. var nbFaces = (indices.length / 3) | 0;
  38511. for (index = 0; index < nbFaces; index++) {
  38512. // get the indexes of the coordinates of each vertex of the facet
  38513. v1x = indices[index * 3] * 3;
  38514. v1y = v1x + 1;
  38515. v1z = v1x + 2;
  38516. v2x = indices[index * 3 + 1] * 3;
  38517. v2y = v2x + 1;
  38518. v2z = v2x + 2;
  38519. v3x = indices[index * 3 + 2] * 3;
  38520. v3y = v3x + 1;
  38521. v3z = v3x + 2;
  38522. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38523. p1p2y = positions[v1y] - positions[v2y];
  38524. p1p2z = positions[v1z] - positions[v2z];
  38525. p3p2x = positions[v3x] - positions[v2x];
  38526. p3p2y = positions[v3y] - positions[v2y];
  38527. p3p2z = positions[v3z] - positions[v2z];
  38528. // compute the face normal with the cross product
  38529. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38530. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38531. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38532. // normalize this normal and store it in the array facetData
  38533. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38534. length = (length === 0) ? 1.0 : length;
  38535. faceNormalx /= length;
  38536. faceNormaly /= length;
  38537. faceNormalz /= length;
  38538. if (computeFacetNormals && options) {
  38539. options.facetNormals[index].x = faceNormalx;
  38540. options.facetNormals[index].y = faceNormaly;
  38541. options.facetNormals[index].z = faceNormalz;
  38542. }
  38543. if (computeFacetPositions && options) {
  38544. // compute and the facet barycenter coordinates in the array facetPositions
  38545. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38546. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38547. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38548. }
  38549. if (computeFacetPartitioning && options) {
  38550. // store the facet indexes in arrays in the main facetPartitioning array :
  38551. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38552. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38553. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38554. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38555. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38556. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38557. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38558. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38559. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38560. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38561. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38562. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38563. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38564. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38565. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38566. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38567. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38568. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38569. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38570. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38571. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38572. // push each facet index in each block containing the vertex
  38573. options.facetPartitioning[block_idx_v1].push(index);
  38574. if (block_idx_v2 != block_idx_v1) {
  38575. options.facetPartitioning[block_idx_v2].push(index);
  38576. }
  38577. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38578. options.facetPartitioning[block_idx_v3].push(index);
  38579. }
  38580. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38581. options.facetPartitioning[block_idx_o].push(index);
  38582. }
  38583. }
  38584. if (computeDepthSort && options && options.facetPositions) {
  38585. var dsf = depthSortedFacets[index];
  38586. dsf.ind = index * 3;
  38587. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38588. }
  38589. // compute the normals anyway
  38590. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38591. normals[v1y] += faceNormaly;
  38592. normals[v1z] += faceNormalz;
  38593. normals[v2x] += faceNormalx;
  38594. normals[v2y] += faceNormaly;
  38595. normals[v2z] += faceNormalz;
  38596. normals[v3x] += faceNormalx;
  38597. normals[v3y] += faceNormaly;
  38598. normals[v3z] += faceNormalz;
  38599. }
  38600. // last normalization of each normal
  38601. for (index = 0; index < normals.length / 3; index++) {
  38602. faceNormalx = normals[index * 3];
  38603. faceNormaly = normals[index * 3 + 1];
  38604. faceNormalz = normals[index * 3 + 2];
  38605. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38606. length = (length === 0) ? 1.0 : length;
  38607. faceNormalx /= length;
  38608. faceNormaly /= length;
  38609. faceNormalz /= length;
  38610. normals[index * 3] = faceNormalx;
  38611. normals[index * 3 + 1] = faceNormaly;
  38612. normals[index * 3 + 2] = faceNormalz;
  38613. }
  38614. };
  38615. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38616. var li = indices.length;
  38617. var ln = normals.length;
  38618. var i;
  38619. var n;
  38620. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38621. switch (sideOrientation) {
  38622. case BABYLON.Mesh.FRONTSIDE:
  38623. // nothing changed
  38624. break;
  38625. case BABYLON.Mesh.BACKSIDE:
  38626. var tmp;
  38627. // indices
  38628. for (i = 0; i < li; i += 3) {
  38629. tmp = indices[i];
  38630. indices[i] = indices[i + 2];
  38631. indices[i + 2] = tmp;
  38632. }
  38633. // normals
  38634. for (n = 0; n < ln; n++) {
  38635. normals[n] = -normals[n];
  38636. }
  38637. break;
  38638. case BABYLON.Mesh.DOUBLESIDE:
  38639. // positions
  38640. var lp = positions.length;
  38641. var l = lp / 3;
  38642. for (var p = 0; p < lp; p++) {
  38643. positions[lp + p] = positions[p];
  38644. }
  38645. // indices
  38646. for (i = 0; i < li; i += 3) {
  38647. indices[i + li] = indices[i + 2] + l;
  38648. indices[i + 1 + li] = indices[i + 1] + l;
  38649. indices[i + 2 + li] = indices[i] + l;
  38650. }
  38651. // normals
  38652. for (n = 0; n < ln; n++) {
  38653. normals[ln + n] = -normals[n];
  38654. }
  38655. // uvs
  38656. var lu = uvs.length;
  38657. var u = 0;
  38658. for (u = 0; u < lu; u++) {
  38659. uvs[u + lu] = uvs[u];
  38660. }
  38661. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38662. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38663. u = 0;
  38664. for (i = 0; i < lu / 2; i++) {
  38665. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38666. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38667. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38668. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38669. u += 2;
  38670. }
  38671. break;
  38672. }
  38673. };
  38674. /**
  38675. * Applies VertexData created from the imported parameters to the geometry
  38676. * @param parsedVertexData the parsed data from an imported file
  38677. * @param geometry the geometry to apply the VertexData to
  38678. */
  38679. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38680. var vertexData = new VertexData();
  38681. // positions
  38682. var positions = parsedVertexData.positions;
  38683. if (positions) {
  38684. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38685. }
  38686. // normals
  38687. var normals = parsedVertexData.normals;
  38688. if (normals) {
  38689. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38690. }
  38691. // tangents
  38692. var tangents = parsedVertexData.tangents;
  38693. if (tangents) {
  38694. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38695. }
  38696. // uvs
  38697. var uvs = parsedVertexData.uvs;
  38698. if (uvs) {
  38699. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38700. }
  38701. // uv2s
  38702. var uv2s = parsedVertexData.uv2s;
  38703. if (uv2s) {
  38704. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38705. }
  38706. // uv3s
  38707. var uv3s = parsedVertexData.uv3s;
  38708. if (uv3s) {
  38709. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38710. }
  38711. // uv4s
  38712. var uv4s = parsedVertexData.uv4s;
  38713. if (uv4s) {
  38714. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38715. }
  38716. // uv5s
  38717. var uv5s = parsedVertexData.uv5s;
  38718. if (uv5s) {
  38719. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38720. }
  38721. // uv6s
  38722. var uv6s = parsedVertexData.uv6s;
  38723. if (uv6s) {
  38724. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38725. }
  38726. // colors
  38727. var colors = parsedVertexData.colors;
  38728. if (colors) {
  38729. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38730. }
  38731. // matricesIndices
  38732. var matricesIndices = parsedVertexData.matricesIndices;
  38733. if (matricesIndices) {
  38734. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38735. }
  38736. // matricesWeights
  38737. var matricesWeights = parsedVertexData.matricesWeights;
  38738. if (matricesWeights) {
  38739. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38740. }
  38741. // indices
  38742. var indices = parsedVertexData.indices;
  38743. if (indices) {
  38744. vertexData.indices = indices;
  38745. }
  38746. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38747. };
  38748. return VertexData;
  38749. }());
  38750. BABYLON.VertexData = VertexData;
  38751. })(BABYLON || (BABYLON = {}));
  38752. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38753. var BABYLON;
  38754. (function (BABYLON) {
  38755. /**
  38756. * Class used to store geometry data (vertex buffers + index buffer)
  38757. */
  38758. var Geometry = /** @class */ (function () {
  38759. /**
  38760. * Creates a new geometry
  38761. * @param id defines the unique ID
  38762. * @param scene defines the hosting scene
  38763. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38764. * @param updatable defines if geometry must be updatable (false by default)
  38765. * @param mesh defines the mesh that will be associated with the geometry
  38766. */
  38767. function Geometry(id, scene, vertexData, updatable, mesh) {
  38768. if (updatable === void 0) { updatable = false; }
  38769. if (mesh === void 0) { mesh = null; }
  38770. /**
  38771. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38772. */
  38773. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38774. this._totalVertices = 0;
  38775. this._isDisposed = false;
  38776. this._indexBufferIsUpdatable = false;
  38777. this.id = id;
  38778. this._engine = scene.getEngine();
  38779. this._meshes = [];
  38780. this._scene = scene;
  38781. //Init vertex buffer cache
  38782. this._vertexBuffers = {};
  38783. this._indices = [];
  38784. this._updatable = updatable;
  38785. // vertexData
  38786. if (vertexData) {
  38787. this.setAllVerticesData(vertexData, updatable);
  38788. }
  38789. else {
  38790. this._totalVertices = 0;
  38791. this._indices = [];
  38792. }
  38793. if (this._engine.getCaps().vertexArrayObject) {
  38794. this._vertexArrayObjects = {};
  38795. }
  38796. // applyToMesh
  38797. if (mesh) {
  38798. if (mesh.getClassName() === "LinesMesh") {
  38799. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38800. this._updateExtend();
  38801. }
  38802. this.applyToMesh(mesh);
  38803. mesh.computeWorldMatrix(true);
  38804. }
  38805. }
  38806. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38807. /**
  38808. * 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
  38809. */
  38810. get: function () {
  38811. return this._boundingBias;
  38812. },
  38813. /**
  38814. * 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
  38815. */
  38816. set: function (value) {
  38817. if (this._boundingBias && this._boundingBias.equals(value)) {
  38818. return;
  38819. }
  38820. this._boundingBias = value.clone();
  38821. this._updateBoundingInfo(true, null);
  38822. },
  38823. enumerable: true,
  38824. configurable: true
  38825. });
  38826. /**
  38827. * Static function used to attach a new empty geometry to a mesh
  38828. * @param mesh defines the mesh to attach the geometry to
  38829. * @returns the new {BABYLON.Geometry}
  38830. */
  38831. Geometry.CreateGeometryForMesh = function (mesh) {
  38832. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38833. geometry.applyToMesh(mesh);
  38834. return geometry;
  38835. };
  38836. Object.defineProperty(Geometry.prototype, "extend", {
  38837. /**
  38838. * Gets the current extend of the geometry
  38839. */
  38840. get: function () {
  38841. return this._extend;
  38842. },
  38843. enumerable: true,
  38844. configurable: true
  38845. });
  38846. /**
  38847. * Gets the hosting scene
  38848. * @returns the hosting {BABYLON.Scene}
  38849. */
  38850. Geometry.prototype.getScene = function () {
  38851. return this._scene;
  38852. };
  38853. /**
  38854. * Gets the hosting engine
  38855. * @returns the hosting {BABYLON.Engine}
  38856. */
  38857. Geometry.prototype.getEngine = function () {
  38858. return this._engine;
  38859. };
  38860. /**
  38861. * Defines if the geometry is ready to use
  38862. * @returns true if the geometry is ready to be used
  38863. */
  38864. Geometry.prototype.isReady = function () {
  38865. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38866. };
  38867. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38868. /**
  38869. * Gets a value indicating that the geometry should not be serialized
  38870. */
  38871. get: function () {
  38872. for (var index = 0; index < this._meshes.length; index++) {
  38873. if (!this._meshes[index].doNotSerialize) {
  38874. return false;
  38875. }
  38876. }
  38877. return true;
  38878. },
  38879. enumerable: true,
  38880. configurable: true
  38881. });
  38882. /** @hidden */
  38883. Geometry.prototype._rebuild = function () {
  38884. if (this._vertexArrayObjects) {
  38885. this._vertexArrayObjects = {};
  38886. }
  38887. // Index buffer
  38888. if (this._meshes.length !== 0 && this._indices) {
  38889. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38890. }
  38891. // Vertex buffers
  38892. for (var key in this._vertexBuffers) {
  38893. var vertexBuffer = this._vertexBuffers[key];
  38894. vertexBuffer._rebuild();
  38895. }
  38896. };
  38897. /**
  38898. * Affects all gemetry data in one call
  38899. * @param vertexData defines the geometry data
  38900. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38901. */
  38902. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38903. vertexData.applyToGeometry(this, updatable);
  38904. this.notifyUpdate();
  38905. };
  38906. /**
  38907. * Set specific vertex data
  38908. * @param kind defines the data kind (Position, normal, etc...)
  38909. * @param data defines the vertex data to use
  38910. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38911. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38912. */
  38913. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38914. if (updatable === void 0) { updatable = false; }
  38915. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38916. this.setVerticesBuffer(buffer);
  38917. };
  38918. /**
  38919. * Removes a specific vertex data
  38920. * @param kind defines the data kind (Position, normal, etc...)
  38921. */
  38922. Geometry.prototype.removeVerticesData = function (kind) {
  38923. if (this._vertexBuffers[kind]) {
  38924. this._vertexBuffers[kind].dispose();
  38925. delete this._vertexBuffers[kind];
  38926. }
  38927. };
  38928. /**
  38929. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38930. * @param buffer defines the vertex buffer to use
  38931. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38932. */
  38933. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38934. if (totalVertices === void 0) { totalVertices = null; }
  38935. var kind = buffer.getKind();
  38936. if (this._vertexBuffers[kind]) {
  38937. this._vertexBuffers[kind].dispose();
  38938. }
  38939. this._vertexBuffers[kind] = buffer;
  38940. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38941. var data = buffer.getData();
  38942. if (totalVertices != null) {
  38943. this._totalVertices = totalVertices;
  38944. }
  38945. else {
  38946. if (data != null) {
  38947. this._totalVertices = data.length / (buffer.byteStride / 4);
  38948. }
  38949. }
  38950. this._updateExtend(data);
  38951. this._resetPointsArrayCache();
  38952. var meshes = this._meshes;
  38953. var numOfMeshes = meshes.length;
  38954. for (var index = 0; index < numOfMeshes; index++) {
  38955. var mesh = meshes[index];
  38956. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38957. mesh._createGlobalSubMesh(false);
  38958. mesh.computeWorldMatrix(true);
  38959. }
  38960. }
  38961. this.notifyUpdate(kind);
  38962. if (this._vertexArrayObjects) {
  38963. this._disposeVertexArrayObjects();
  38964. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38965. }
  38966. };
  38967. /**
  38968. * Update a specific vertex buffer
  38969. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38970. * It will do nothing if the buffer is not updatable
  38971. * @param kind defines the data kind (Position, normal, etc...)
  38972. * @param data defines the data to use
  38973. * @param offset defines the offset in the target buffer where to store the data
  38974. * @param useBytes set to true if the offset is in bytes
  38975. */
  38976. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38977. if (useBytes === void 0) { useBytes = false; }
  38978. var vertexBuffer = this.getVertexBuffer(kind);
  38979. if (!vertexBuffer) {
  38980. return;
  38981. }
  38982. vertexBuffer.updateDirectly(data, offset, useBytes);
  38983. this.notifyUpdate(kind);
  38984. };
  38985. /**
  38986. * Update a specific vertex buffer
  38987. * This function will create a new buffer if the current one is not updatable
  38988. * @param kind defines the data kind (Position, normal, etc...)
  38989. * @param data defines the data to use
  38990. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38991. */
  38992. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38993. if (updateExtends === void 0) { updateExtends = false; }
  38994. var vertexBuffer = this.getVertexBuffer(kind);
  38995. if (!vertexBuffer) {
  38996. return;
  38997. }
  38998. vertexBuffer.update(data);
  38999. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39000. this._updateBoundingInfo(updateExtends, data);
  39001. }
  39002. this.notifyUpdate(kind);
  39003. };
  39004. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39005. if (updateExtends) {
  39006. this._updateExtend(data);
  39007. }
  39008. var meshes = this._meshes;
  39009. var numOfMeshes = meshes.length;
  39010. this._resetPointsArrayCache();
  39011. for (var index = 0; index < numOfMeshes; index++) {
  39012. var mesh = meshes[index];
  39013. if (updateExtends) {
  39014. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39015. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39016. var subMesh = mesh.subMeshes[subIndex];
  39017. subMesh.refreshBoundingInfo();
  39018. }
  39019. }
  39020. }
  39021. };
  39022. /** @hidden */
  39023. Geometry.prototype._bind = function (effect, indexToBind) {
  39024. if (!effect) {
  39025. return;
  39026. }
  39027. if (indexToBind === undefined) {
  39028. indexToBind = this._indexBuffer;
  39029. }
  39030. var vbs = this.getVertexBuffers();
  39031. if (!vbs) {
  39032. return;
  39033. }
  39034. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39035. this._engine.bindBuffers(vbs, indexToBind, effect);
  39036. return;
  39037. }
  39038. // Using VAO
  39039. if (!this._vertexArrayObjects[effect.key]) {
  39040. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39041. }
  39042. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39043. };
  39044. /**
  39045. * Gets total number of vertices
  39046. * @returns the total number of vertices
  39047. */
  39048. Geometry.prototype.getTotalVertices = function () {
  39049. if (!this.isReady()) {
  39050. return 0;
  39051. }
  39052. return this._totalVertices;
  39053. };
  39054. /**
  39055. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39056. * @param kind defines the data kind (Position, normal, etc...)
  39057. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39058. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39059. * @returns a float array containing vertex data
  39060. */
  39061. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39062. var vertexBuffer = this.getVertexBuffer(kind);
  39063. if (!vertexBuffer) {
  39064. return null;
  39065. }
  39066. var data = vertexBuffer.getData();
  39067. if (!data) {
  39068. return null;
  39069. }
  39070. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39071. var count = this._totalVertices * vertexBuffer.getSize();
  39072. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39073. var copy_1 = new Array(count);
  39074. vertexBuffer.forEach(count, function (value, index) {
  39075. copy_1[index] = value;
  39076. });
  39077. return copy_1;
  39078. }
  39079. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39080. if (data instanceof Array) {
  39081. var offset = vertexBuffer.byteOffset / 4;
  39082. return BABYLON.Tools.Slice(data, offset, offset + count);
  39083. }
  39084. else if (data instanceof ArrayBuffer) {
  39085. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39086. }
  39087. else {
  39088. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39089. }
  39090. }
  39091. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39092. return BABYLON.Tools.Slice(data);
  39093. }
  39094. return data;
  39095. };
  39096. /**
  39097. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39098. * @param kind defines the data kind (Position, normal, etc...)
  39099. * @returns true if the vertex buffer with the specified kind is updatable
  39100. */
  39101. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39102. var vb = this._vertexBuffers[kind];
  39103. if (!vb) {
  39104. return false;
  39105. }
  39106. return vb.isUpdatable();
  39107. };
  39108. /**
  39109. * Gets a specific vertex buffer
  39110. * @param kind defines the data kind (Position, normal, etc...)
  39111. * @returns a {BABYLON.VertexBuffer}
  39112. */
  39113. Geometry.prototype.getVertexBuffer = function (kind) {
  39114. if (!this.isReady()) {
  39115. return null;
  39116. }
  39117. return this._vertexBuffers[kind];
  39118. };
  39119. /**
  39120. * Returns all vertex buffers
  39121. * @return an object holding all vertex buffers indexed by kind
  39122. */
  39123. Geometry.prototype.getVertexBuffers = function () {
  39124. if (!this.isReady()) {
  39125. return null;
  39126. }
  39127. return this._vertexBuffers;
  39128. };
  39129. /**
  39130. * Gets a boolean indicating if specific vertex buffer is present
  39131. * @param kind defines the data kind (Position, normal, etc...)
  39132. * @returns true if data is present
  39133. */
  39134. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39135. if (!this._vertexBuffers) {
  39136. if (this._delayInfo) {
  39137. return this._delayInfo.indexOf(kind) !== -1;
  39138. }
  39139. return false;
  39140. }
  39141. return this._vertexBuffers[kind] !== undefined;
  39142. };
  39143. /**
  39144. * Gets a list of all attached data kinds (Position, normal, etc...)
  39145. * @returns a list of string containing all kinds
  39146. */
  39147. Geometry.prototype.getVerticesDataKinds = function () {
  39148. var result = [];
  39149. var kind;
  39150. if (!this._vertexBuffers && this._delayInfo) {
  39151. for (kind in this._delayInfo) {
  39152. result.push(kind);
  39153. }
  39154. }
  39155. else {
  39156. for (kind in this._vertexBuffers) {
  39157. result.push(kind);
  39158. }
  39159. }
  39160. return result;
  39161. };
  39162. /**
  39163. * Update index buffer
  39164. * @param indices defines the indices to store in the index buffer
  39165. * @param offset defines the offset in the target buffer where to store the data
  39166. */
  39167. Geometry.prototype.updateIndices = function (indices, offset) {
  39168. if (!this._indexBuffer) {
  39169. return;
  39170. }
  39171. if (!this._indexBufferIsUpdatable) {
  39172. this.setIndices(indices, null, true);
  39173. }
  39174. else {
  39175. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39176. }
  39177. };
  39178. /**
  39179. * Creates a new index buffer
  39180. * @param indices defines the indices to store in the index buffer
  39181. * @param totalVertices defines the total number of vertices (could be null)
  39182. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39183. */
  39184. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39185. if (totalVertices === void 0) { totalVertices = null; }
  39186. if (updatable === void 0) { updatable = false; }
  39187. if (this._indexBuffer) {
  39188. this._engine._releaseBuffer(this._indexBuffer);
  39189. }
  39190. this._disposeVertexArrayObjects();
  39191. this._indices = indices;
  39192. this._indexBufferIsUpdatable = updatable;
  39193. if (this._meshes.length !== 0 && this._indices) {
  39194. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39195. }
  39196. if (totalVertices != undefined) { // including null and undefined
  39197. this._totalVertices = totalVertices;
  39198. }
  39199. var meshes = this._meshes;
  39200. var numOfMeshes = meshes.length;
  39201. for (var index = 0; index < numOfMeshes; index++) {
  39202. meshes[index]._createGlobalSubMesh(true);
  39203. }
  39204. this.notifyUpdate();
  39205. };
  39206. /**
  39207. * Return the total number of indices
  39208. * @returns the total number of indices
  39209. */
  39210. Geometry.prototype.getTotalIndices = function () {
  39211. if (!this.isReady()) {
  39212. return 0;
  39213. }
  39214. return this._indices.length;
  39215. };
  39216. /**
  39217. * Gets the index buffer array
  39218. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39219. * @returns the index buffer array
  39220. */
  39221. Geometry.prototype.getIndices = function (copyWhenShared) {
  39222. if (!this.isReady()) {
  39223. return null;
  39224. }
  39225. var orig = this._indices;
  39226. if (!copyWhenShared || this._meshes.length === 1) {
  39227. return orig;
  39228. }
  39229. else {
  39230. var len = orig.length;
  39231. var copy = [];
  39232. for (var i = 0; i < len; i++) {
  39233. copy.push(orig[i]);
  39234. }
  39235. return copy;
  39236. }
  39237. };
  39238. /**
  39239. * Gets the index buffer
  39240. * @return the index buffer
  39241. */
  39242. Geometry.prototype.getIndexBuffer = function () {
  39243. if (!this.isReady()) {
  39244. return null;
  39245. }
  39246. return this._indexBuffer;
  39247. };
  39248. /** @hidden */
  39249. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39250. if (effect === void 0) { effect = null; }
  39251. if (!effect || !this._vertexArrayObjects) {
  39252. return;
  39253. }
  39254. if (this._vertexArrayObjects[effect.key]) {
  39255. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39256. delete this._vertexArrayObjects[effect.key];
  39257. }
  39258. };
  39259. /**
  39260. * Release the associated resources for a specific mesh
  39261. * @param mesh defines the source mesh
  39262. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39263. */
  39264. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39265. var meshes = this._meshes;
  39266. var index = meshes.indexOf(mesh);
  39267. if (index === -1) {
  39268. return;
  39269. }
  39270. meshes.splice(index, 1);
  39271. mesh._geometry = null;
  39272. if (meshes.length === 0 && shouldDispose) {
  39273. this.dispose();
  39274. }
  39275. };
  39276. /**
  39277. * Apply current geometry to a given mesh
  39278. * @param mesh defines the mesh to apply geometry to
  39279. */
  39280. Geometry.prototype.applyToMesh = function (mesh) {
  39281. if (mesh._geometry === this) {
  39282. return;
  39283. }
  39284. var previousGeometry = mesh._geometry;
  39285. if (previousGeometry) {
  39286. previousGeometry.releaseForMesh(mesh);
  39287. }
  39288. var meshes = this._meshes;
  39289. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39290. mesh._geometry = this;
  39291. this._scene.pushGeometry(this);
  39292. meshes.push(mesh);
  39293. if (this.isReady()) {
  39294. this._applyToMesh(mesh);
  39295. }
  39296. else {
  39297. mesh._boundingInfo = this._boundingInfo;
  39298. }
  39299. };
  39300. Geometry.prototype._updateExtend = function (data) {
  39301. if (data === void 0) { data = null; }
  39302. if (!data) {
  39303. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39304. }
  39305. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39306. };
  39307. Geometry.prototype._applyToMesh = function (mesh) {
  39308. var numOfMeshes = this._meshes.length;
  39309. // vertexBuffers
  39310. for (var kind in this._vertexBuffers) {
  39311. if (numOfMeshes === 1) {
  39312. this._vertexBuffers[kind].create();
  39313. }
  39314. var buffer = this._vertexBuffers[kind].getBuffer();
  39315. if (buffer)
  39316. buffer.references = numOfMeshes;
  39317. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39318. if (!this._extend) {
  39319. this._updateExtend();
  39320. }
  39321. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39322. mesh._createGlobalSubMesh(false);
  39323. //bounding info was just created again, world matrix should be applied again.
  39324. mesh._updateBoundingInfo();
  39325. }
  39326. }
  39327. // indexBuffer
  39328. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39329. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39330. }
  39331. if (this._indexBuffer) {
  39332. this._indexBuffer.references = numOfMeshes;
  39333. }
  39334. };
  39335. Geometry.prototype.notifyUpdate = function (kind) {
  39336. if (this.onGeometryUpdated) {
  39337. this.onGeometryUpdated(this, kind);
  39338. }
  39339. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39340. var mesh = _a[_i];
  39341. mesh._markSubMeshesAsAttributesDirty();
  39342. }
  39343. };
  39344. /**
  39345. * Load the geometry if it was flagged as delay loaded
  39346. * @param scene defines the hosting scene
  39347. * @param onLoaded defines a callback called when the geometry is loaded
  39348. */
  39349. Geometry.prototype.load = function (scene, onLoaded) {
  39350. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39351. return;
  39352. }
  39353. if (this.isReady()) {
  39354. if (onLoaded) {
  39355. onLoaded();
  39356. }
  39357. return;
  39358. }
  39359. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39360. this._queueLoad(scene, onLoaded);
  39361. };
  39362. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39363. var _this = this;
  39364. if (!this.delayLoadingFile) {
  39365. return;
  39366. }
  39367. scene._addPendingData(this);
  39368. scene._loadFile(this.delayLoadingFile, function (data) {
  39369. if (!_this._delayLoadingFunction) {
  39370. return;
  39371. }
  39372. _this._delayLoadingFunction(JSON.parse(data), _this);
  39373. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39374. _this._delayInfo = [];
  39375. scene._removePendingData(_this);
  39376. var meshes = _this._meshes;
  39377. var numOfMeshes = meshes.length;
  39378. for (var index = 0; index < numOfMeshes; index++) {
  39379. _this._applyToMesh(meshes[index]);
  39380. }
  39381. if (onLoaded) {
  39382. onLoaded();
  39383. }
  39384. }, undefined, true);
  39385. };
  39386. /**
  39387. * Invert the geometry to move from a right handed system to a left handed one.
  39388. */
  39389. Geometry.prototype.toLeftHanded = function () {
  39390. // Flip faces
  39391. var tIndices = this.getIndices(false);
  39392. if (tIndices != null && tIndices.length > 0) {
  39393. for (var i = 0; i < tIndices.length; i += 3) {
  39394. var tTemp = tIndices[i + 0];
  39395. tIndices[i + 0] = tIndices[i + 2];
  39396. tIndices[i + 2] = tTemp;
  39397. }
  39398. this.setIndices(tIndices);
  39399. }
  39400. // Negate position.z
  39401. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39402. if (tPositions != null && tPositions.length > 0) {
  39403. for (var i = 0; i < tPositions.length; i += 3) {
  39404. tPositions[i + 2] = -tPositions[i + 2];
  39405. }
  39406. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39407. }
  39408. // Negate normal.z
  39409. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39410. if (tNormals != null && tNormals.length > 0) {
  39411. for (var i = 0; i < tNormals.length; i += 3) {
  39412. tNormals[i + 2] = -tNormals[i + 2];
  39413. }
  39414. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39415. }
  39416. };
  39417. // Cache
  39418. /** @hidden */
  39419. Geometry.prototype._resetPointsArrayCache = function () {
  39420. this._positions = null;
  39421. };
  39422. /** @hidden */
  39423. Geometry.prototype._generatePointsArray = function () {
  39424. if (this._positions)
  39425. return true;
  39426. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39427. if (!data || data.length === 0) {
  39428. return false;
  39429. }
  39430. this._positions = [];
  39431. for (var index = 0; index < data.length; index += 3) {
  39432. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39433. }
  39434. return true;
  39435. };
  39436. /**
  39437. * Gets a value indicating if the geometry is disposed
  39438. * @returns true if the geometry was disposed
  39439. */
  39440. Geometry.prototype.isDisposed = function () {
  39441. return this._isDisposed;
  39442. };
  39443. Geometry.prototype._disposeVertexArrayObjects = function () {
  39444. if (this._vertexArrayObjects) {
  39445. for (var kind in this._vertexArrayObjects) {
  39446. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39447. }
  39448. this._vertexArrayObjects = {};
  39449. }
  39450. };
  39451. /**
  39452. * Free all associated resources
  39453. */
  39454. Geometry.prototype.dispose = function () {
  39455. var meshes = this._meshes;
  39456. var numOfMeshes = meshes.length;
  39457. var index;
  39458. for (index = 0; index < numOfMeshes; index++) {
  39459. this.releaseForMesh(meshes[index]);
  39460. }
  39461. this._meshes = [];
  39462. this._disposeVertexArrayObjects();
  39463. for (var kind in this._vertexBuffers) {
  39464. this._vertexBuffers[kind].dispose();
  39465. }
  39466. this._vertexBuffers = {};
  39467. this._totalVertices = 0;
  39468. if (this._indexBuffer) {
  39469. this._engine._releaseBuffer(this._indexBuffer);
  39470. }
  39471. this._indexBuffer = null;
  39472. this._indices = [];
  39473. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39474. this.delayLoadingFile = null;
  39475. this._delayLoadingFunction = null;
  39476. this._delayInfo = [];
  39477. this._boundingInfo = null;
  39478. this._scene.removeGeometry(this);
  39479. this._isDisposed = true;
  39480. };
  39481. /**
  39482. * Clone the current geometry into a new geometry
  39483. * @param id defines the unique ID of the new geometry
  39484. * @returns a new geometry object
  39485. */
  39486. Geometry.prototype.copy = function (id) {
  39487. var vertexData = new BABYLON.VertexData();
  39488. vertexData.indices = [];
  39489. var indices = this.getIndices();
  39490. if (indices) {
  39491. for (var index = 0; index < indices.length; index++) {
  39492. vertexData.indices.push(indices[index]);
  39493. }
  39494. }
  39495. var updatable = false;
  39496. var stopChecking = false;
  39497. var kind;
  39498. for (kind in this._vertexBuffers) {
  39499. // using slice() to make a copy of the array and not just reference it
  39500. var data = this.getVerticesData(kind);
  39501. if (data instanceof Float32Array) {
  39502. vertexData.set(new Float32Array(data), kind);
  39503. }
  39504. else {
  39505. vertexData.set(data.slice(0), kind);
  39506. }
  39507. if (!stopChecking) {
  39508. var vb = this.getVertexBuffer(kind);
  39509. if (vb) {
  39510. updatable = vb.isUpdatable();
  39511. stopChecking = !updatable;
  39512. }
  39513. }
  39514. }
  39515. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39516. geometry.delayLoadState = this.delayLoadState;
  39517. geometry.delayLoadingFile = this.delayLoadingFile;
  39518. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39519. for (kind in this._delayInfo) {
  39520. geometry._delayInfo = geometry._delayInfo || [];
  39521. geometry._delayInfo.push(kind);
  39522. }
  39523. // Bounding info
  39524. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39525. return geometry;
  39526. };
  39527. /**
  39528. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39529. * @return a JSON representation of the current geometry data (without the vertices data)
  39530. */
  39531. Geometry.prototype.serialize = function () {
  39532. var serializationObject = {};
  39533. serializationObject.id = this.id;
  39534. serializationObject.updatable = this._updatable;
  39535. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39536. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39537. }
  39538. return serializationObject;
  39539. };
  39540. Geometry.prototype.toNumberArray = function (origin) {
  39541. if (Array.isArray(origin)) {
  39542. return origin;
  39543. }
  39544. else {
  39545. return Array.prototype.slice.call(origin);
  39546. }
  39547. };
  39548. /**
  39549. * Serialize all vertices data into a JSON oject
  39550. * @returns a JSON representation of the current geometry data
  39551. */
  39552. Geometry.prototype.serializeVerticeData = function () {
  39553. var serializationObject = this.serialize();
  39554. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39555. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39556. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39557. serializationObject.positions._updatable = true;
  39558. }
  39559. }
  39560. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39561. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39562. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39563. serializationObject.normals._updatable = true;
  39564. }
  39565. }
  39566. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39567. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39568. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39569. serializationObject.tangets._updatable = true;
  39570. }
  39571. }
  39572. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39573. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39574. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39575. serializationObject.uvs._updatable = true;
  39576. }
  39577. }
  39578. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39579. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39580. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39581. serializationObject.uv2s._updatable = true;
  39582. }
  39583. }
  39584. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39585. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39586. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39587. serializationObject.uv3s._updatable = true;
  39588. }
  39589. }
  39590. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39591. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39592. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39593. serializationObject.uv4s._updatable = true;
  39594. }
  39595. }
  39596. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39597. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39598. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39599. serializationObject.uv5s._updatable = true;
  39600. }
  39601. }
  39602. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39603. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39604. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39605. serializationObject.uv6s._updatable = true;
  39606. }
  39607. }
  39608. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39609. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39610. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39611. serializationObject.colors._updatable = true;
  39612. }
  39613. }
  39614. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39615. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39616. serializationObject.matricesIndices._isExpanded = true;
  39617. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39618. serializationObject.matricesIndices._updatable = true;
  39619. }
  39620. }
  39621. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39622. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39623. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39624. serializationObject.matricesWeights._updatable = true;
  39625. }
  39626. }
  39627. serializationObject.indices = this.toNumberArray(this.getIndices());
  39628. return serializationObject;
  39629. };
  39630. // Statics
  39631. /**
  39632. * Extracts a clone of a mesh geometry
  39633. * @param mesh defines the source mesh
  39634. * @param id defines the unique ID of the new geometry object
  39635. * @returns the new geometry object
  39636. */
  39637. Geometry.ExtractFromMesh = function (mesh, id) {
  39638. var geometry = mesh._geometry;
  39639. if (!geometry) {
  39640. return null;
  39641. }
  39642. return geometry.copy(id);
  39643. };
  39644. /**
  39645. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39646. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39647. * Be aware Math.random() could cause collisions, but:
  39648. * "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"
  39649. * @returns a string containing a new GUID
  39650. */
  39651. Geometry.RandomId = function () {
  39652. return BABYLON.Tools.RandomId();
  39653. };
  39654. /** @hidden */
  39655. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39656. var scene = mesh.getScene();
  39657. // Geometry
  39658. var geometryId = parsedGeometry.geometryId;
  39659. if (geometryId) {
  39660. var geometry = scene.getGeometryByID(geometryId);
  39661. if (geometry) {
  39662. geometry.applyToMesh(mesh);
  39663. }
  39664. }
  39665. else if (parsedGeometry instanceof ArrayBuffer) {
  39666. var binaryInfo = mesh._binaryInfo;
  39667. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39668. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39669. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39670. }
  39671. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39672. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39673. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39674. }
  39675. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39676. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39677. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39678. }
  39679. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39680. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39681. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39682. }
  39683. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39684. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39685. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39686. }
  39687. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39688. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39689. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39690. }
  39691. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39692. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39693. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39694. }
  39695. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39696. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39697. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39698. }
  39699. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39700. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39701. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39702. }
  39703. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39704. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39705. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39706. }
  39707. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39708. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39709. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39710. }
  39711. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39712. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39713. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39714. }
  39715. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39716. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39717. mesh.setIndices(indicesData, null);
  39718. }
  39719. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39720. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39721. mesh.subMeshes = [];
  39722. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39723. var materialIndex = subMeshesData[(i * 5) + 0];
  39724. var verticesStart = subMeshesData[(i * 5) + 1];
  39725. var verticesCount = subMeshesData[(i * 5) + 2];
  39726. var indexStart = subMeshesData[(i * 5) + 3];
  39727. var indexCount = subMeshesData[(i * 5) + 4];
  39728. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39729. }
  39730. }
  39731. }
  39732. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39733. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39734. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39735. if (parsedGeometry.tangents) {
  39736. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39737. }
  39738. if (parsedGeometry.uvs) {
  39739. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39740. }
  39741. if (parsedGeometry.uvs2) {
  39742. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39743. }
  39744. if (parsedGeometry.uvs3) {
  39745. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39746. }
  39747. if (parsedGeometry.uvs4) {
  39748. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39749. }
  39750. if (parsedGeometry.uvs5) {
  39751. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39752. }
  39753. if (parsedGeometry.uvs6) {
  39754. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39755. }
  39756. if (parsedGeometry.colors) {
  39757. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39758. }
  39759. if (parsedGeometry.matricesIndices) {
  39760. if (!parsedGeometry.matricesIndices._isExpanded) {
  39761. var floatIndices = [];
  39762. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39763. var matricesIndex = parsedGeometry.matricesIndices[i];
  39764. floatIndices.push(matricesIndex & 0x000000FF);
  39765. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39766. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39767. floatIndices.push(matricesIndex >> 24);
  39768. }
  39769. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39770. }
  39771. else {
  39772. delete parsedGeometry.matricesIndices._isExpanded;
  39773. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39774. }
  39775. }
  39776. if (parsedGeometry.matricesIndicesExtra) {
  39777. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39778. var floatIndices = [];
  39779. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39780. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39781. floatIndices.push(matricesIndex & 0x000000FF);
  39782. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39783. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39784. floatIndices.push(matricesIndex >> 24);
  39785. }
  39786. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39787. }
  39788. else {
  39789. delete parsedGeometry.matricesIndices._isExpanded;
  39790. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39791. }
  39792. }
  39793. if (parsedGeometry.matricesWeights) {
  39794. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39795. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39796. }
  39797. if (parsedGeometry.matricesWeightsExtra) {
  39798. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39799. }
  39800. mesh.setIndices(parsedGeometry.indices, null);
  39801. }
  39802. // SubMeshes
  39803. if (parsedGeometry.subMeshes) {
  39804. mesh.subMeshes = [];
  39805. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39806. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39807. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39808. }
  39809. }
  39810. // Flat shading
  39811. if (mesh._shouldGenerateFlatShading) {
  39812. mesh.convertToFlatShadedMesh();
  39813. delete mesh._shouldGenerateFlatShading;
  39814. }
  39815. // Update
  39816. mesh.computeWorldMatrix(true);
  39817. // Octree
  39818. var sceneOctree = scene.selectionOctree;
  39819. if (sceneOctree !== undefined && sceneOctree !== null) {
  39820. sceneOctree.addMesh(mesh);
  39821. }
  39822. };
  39823. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39824. var epsilon = 1e-3;
  39825. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39826. return;
  39827. }
  39828. var noInfluenceBoneIndex = 0.0;
  39829. if (parsedGeometry.skeletonId > -1) {
  39830. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39831. if (!skeleton) {
  39832. return;
  39833. }
  39834. noInfluenceBoneIndex = skeleton.bones.length;
  39835. }
  39836. else {
  39837. return;
  39838. }
  39839. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39840. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39841. var matricesWeights = parsedGeometry.matricesWeights;
  39842. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39843. var influencers = parsedGeometry.numBoneInfluencer;
  39844. var size = matricesWeights.length;
  39845. for (var i = 0; i < size; i += 4) {
  39846. var weight = 0.0;
  39847. var firstZeroWeight = -1;
  39848. for (var j = 0; j < 4; j++) {
  39849. var w = matricesWeights[i + j];
  39850. weight += w;
  39851. if (w < epsilon && firstZeroWeight < 0) {
  39852. firstZeroWeight = j;
  39853. }
  39854. }
  39855. if (matricesWeightsExtra) {
  39856. for (var j = 0; j < 4; j++) {
  39857. var w = matricesWeightsExtra[i + j];
  39858. weight += w;
  39859. if (w < epsilon && firstZeroWeight < 0) {
  39860. firstZeroWeight = j + 4;
  39861. }
  39862. }
  39863. }
  39864. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39865. firstZeroWeight = influencers - 1;
  39866. }
  39867. if (weight > epsilon) {
  39868. var mweight = 1.0 / weight;
  39869. for (var j = 0; j < 4; j++) {
  39870. matricesWeights[i + j] *= mweight;
  39871. }
  39872. if (matricesWeightsExtra) {
  39873. for (var j = 0; j < 4; j++) {
  39874. matricesWeightsExtra[i + j] *= mweight;
  39875. }
  39876. }
  39877. }
  39878. else {
  39879. if (firstZeroWeight >= 4) {
  39880. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39881. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39882. }
  39883. else {
  39884. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39885. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39886. }
  39887. }
  39888. }
  39889. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39890. if (parsedGeometry.matricesWeightsExtra) {
  39891. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39892. }
  39893. };
  39894. /**
  39895. * Create a new geometry from persisted data (Using .babylon file format)
  39896. * @param parsedVertexData defines the persisted data
  39897. * @param scene defines the hosting scene
  39898. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39899. * @returns the new geometry object
  39900. */
  39901. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39902. if (scene.getGeometryByID(parsedVertexData.id)) {
  39903. return null; // null since geometry could be something else than a box...
  39904. }
  39905. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39906. if (BABYLON.Tags) {
  39907. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39908. }
  39909. if (parsedVertexData.delayLoadingFile) {
  39910. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39911. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39912. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39913. geometry._delayInfo = [];
  39914. if (parsedVertexData.hasUVs) {
  39915. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39916. }
  39917. if (parsedVertexData.hasUVs2) {
  39918. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39919. }
  39920. if (parsedVertexData.hasUVs3) {
  39921. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39922. }
  39923. if (parsedVertexData.hasUVs4) {
  39924. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39925. }
  39926. if (parsedVertexData.hasUVs5) {
  39927. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39928. }
  39929. if (parsedVertexData.hasUVs6) {
  39930. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39931. }
  39932. if (parsedVertexData.hasColors) {
  39933. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39934. }
  39935. if (parsedVertexData.hasMatricesIndices) {
  39936. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39937. }
  39938. if (parsedVertexData.hasMatricesWeights) {
  39939. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39940. }
  39941. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39942. }
  39943. else {
  39944. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39945. }
  39946. scene.pushGeometry(geometry, true);
  39947. return geometry;
  39948. };
  39949. return Geometry;
  39950. }());
  39951. BABYLON.Geometry = Geometry;
  39952. // Primitives
  39953. /// Abstract class
  39954. /**
  39955. * Abstract class used to provide common services for all typed geometries
  39956. * @hidden
  39957. */
  39958. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39959. __extends(_PrimitiveGeometry, _super);
  39960. /**
  39961. * Creates a new typed geometry
  39962. * @param id defines the unique ID of the geometry
  39963. * @param scene defines the hosting scene
  39964. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39965. * @param mesh defines the hosting mesh (can be null)
  39966. */
  39967. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39968. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39969. if (mesh === void 0) { mesh = null; }
  39970. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39971. _this._canBeRegenerated = _canBeRegenerated;
  39972. _this._beingRegenerated = true;
  39973. _this.regenerate();
  39974. _this._beingRegenerated = false;
  39975. return _this;
  39976. }
  39977. /**
  39978. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39979. * @returns true if the geometry can be regenerated
  39980. */
  39981. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39982. return this._canBeRegenerated;
  39983. };
  39984. /**
  39985. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39986. */
  39987. _PrimitiveGeometry.prototype.regenerate = function () {
  39988. if (!this._canBeRegenerated) {
  39989. return;
  39990. }
  39991. this._beingRegenerated = true;
  39992. this.setAllVerticesData(this._regenerateVertexData(), false);
  39993. this._beingRegenerated = false;
  39994. };
  39995. /**
  39996. * Clone the geometry
  39997. * @param id defines the unique ID of the new geometry
  39998. * @returns the new geometry
  39999. */
  40000. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40001. return _super.prototype.copy.call(this, id);
  40002. };
  40003. // overrides
  40004. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40005. if (!this._beingRegenerated) {
  40006. return;
  40007. }
  40008. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40009. };
  40010. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40011. if (!this._beingRegenerated) {
  40012. return;
  40013. }
  40014. _super.prototype.setVerticesData.call(this, kind, data, false);
  40015. };
  40016. // to override
  40017. /** @hidden */
  40018. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40019. throw new Error("Abstract method");
  40020. };
  40021. _PrimitiveGeometry.prototype.copy = function (id) {
  40022. throw new Error("Must be overriden in sub-classes.");
  40023. };
  40024. _PrimitiveGeometry.prototype.serialize = function () {
  40025. var serializationObject = _super.prototype.serialize.call(this);
  40026. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40027. return serializationObject;
  40028. };
  40029. return _PrimitiveGeometry;
  40030. }(Geometry));
  40031. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40032. /**
  40033. * Creates a ribbon geometry
  40034. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40035. */
  40036. var RibbonGeometry = /** @class */ (function (_super) {
  40037. __extends(RibbonGeometry, _super);
  40038. /**
  40039. * Creates a ribbon geometry
  40040. * @param id defines the unique ID of the geometry
  40041. * @param scene defines the hosting scene
  40042. * @param pathArray defines the array of paths to use
  40043. * @param closeArray defines if the last path and the first path must be joined
  40044. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40045. * @param offset defines the offset between points
  40046. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40047. * @param mesh defines the hosting mesh (can be null)
  40048. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40049. */
  40050. function RibbonGeometry(id, scene,
  40051. /**
  40052. * Defines the array of paths to use
  40053. */
  40054. pathArray,
  40055. /**
  40056. * Defines if the last and first points of each path in your pathArray must be joined
  40057. */
  40058. closeArray,
  40059. /**
  40060. * Defines if the last and first points of each path in your pathArray must be joined
  40061. */
  40062. closePath,
  40063. /**
  40064. * Defines the offset between points
  40065. */
  40066. offset, canBeRegenerated, mesh,
  40067. /**
  40068. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40069. */
  40070. side) {
  40071. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40072. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40073. _this.pathArray = pathArray;
  40074. _this.closeArray = closeArray;
  40075. _this.closePath = closePath;
  40076. _this.offset = offset;
  40077. _this.side = side;
  40078. return _this;
  40079. }
  40080. /** @hidden */
  40081. RibbonGeometry.prototype._regenerateVertexData = function () {
  40082. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40083. };
  40084. RibbonGeometry.prototype.copy = function (id) {
  40085. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40086. };
  40087. return RibbonGeometry;
  40088. }(_PrimitiveGeometry));
  40089. BABYLON.RibbonGeometry = RibbonGeometry;
  40090. /**
  40091. * Creates a box geometry
  40092. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40093. */
  40094. var BoxGeometry = /** @class */ (function (_super) {
  40095. __extends(BoxGeometry, _super);
  40096. /**
  40097. * Creates a box geometry
  40098. * @param id defines the unique ID of the geometry
  40099. * @param scene defines the hosting scene
  40100. * @param size defines the zise of the box (width, height and depth are the same)
  40101. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40102. * @param mesh defines the hosting mesh (can be null)
  40103. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40104. */
  40105. function BoxGeometry(id, scene,
  40106. /**
  40107. * Defines the zise of the box (width, height and depth are the same)
  40108. */
  40109. size, canBeRegenerated, mesh,
  40110. /**
  40111. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40112. */
  40113. side) {
  40114. if (mesh === void 0) { mesh = null; }
  40115. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40116. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40117. _this.size = size;
  40118. _this.side = side;
  40119. return _this;
  40120. }
  40121. BoxGeometry.prototype._regenerateVertexData = function () {
  40122. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40123. };
  40124. BoxGeometry.prototype.copy = function (id) {
  40125. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40126. };
  40127. BoxGeometry.prototype.serialize = function () {
  40128. var serializationObject = _super.prototype.serialize.call(this);
  40129. serializationObject.size = this.size;
  40130. return serializationObject;
  40131. };
  40132. BoxGeometry.Parse = function (parsedBox, scene) {
  40133. if (scene.getGeometryByID(parsedBox.id)) {
  40134. return null; // null since geometry could be something else than a box...
  40135. }
  40136. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40137. if (BABYLON.Tags) {
  40138. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40139. }
  40140. scene.pushGeometry(box, true);
  40141. return box;
  40142. };
  40143. return BoxGeometry;
  40144. }(_PrimitiveGeometry));
  40145. BABYLON.BoxGeometry = BoxGeometry;
  40146. /**
  40147. * Creates a sphere geometry
  40148. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40149. */
  40150. var SphereGeometry = /** @class */ (function (_super) {
  40151. __extends(SphereGeometry, _super);
  40152. /**
  40153. * Create a new sphere geometry
  40154. * @param id defines the unique ID of the geometry
  40155. * @param scene defines the hosting scene
  40156. * @param segments defines the number of segments to use to create the sphere
  40157. * @param diameter defines the diameter of the sphere
  40158. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40159. * @param mesh defines the hosting mesh (can be null)
  40160. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40161. */
  40162. function SphereGeometry(id, scene,
  40163. /**
  40164. * Defines the number of segments to use to create the sphere
  40165. */
  40166. segments,
  40167. /**
  40168. * Defines the diameter of the sphere
  40169. */
  40170. diameter, canBeRegenerated, mesh,
  40171. /**
  40172. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40173. */
  40174. side) {
  40175. if (mesh === void 0) { mesh = null; }
  40176. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40177. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40178. _this.segments = segments;
  40179. _this.diameter = diameter;
  40180. _this.side = side;
  40181. return _this;
  40182. }
  40183. SphereGeometry.prototype._regenerateVertexData = function () {
  40184. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40185. };
  40186. SphereGeometry.prototype.copy = function (id) {
  40187. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40188. };
  40189. SphereGeometry.prototype.serialize = function () {
  40190. var serializationObject = _super.prototype.serialize.call(this);
  40191. serializationObject.segments = this.segments;
  40192. serializationObject.diameter = this.diameter;
  40193. return serializationObject;
  40194. };
  40195. SphereGeometry.Parse = function (parsedSphere, scene) {
  40196. if (scene.getGeometryByID(parsedSphere.id)) {
  40197. return null; // null since geometry could be something else than a sphere...
  40198. }
  40199. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40200. if (BABYLON.Tags) {
  40201. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40202. }
  40203. scene.pushGeometry(sphere, true);
  40204. return sphere;
  40205. };
  40206. return SphereGeometry;
  40207. }(_PrimitiveGeometry));
  40208. BABYLON.SphereGeometry = SphereGeometry;
  40209. /**
  40210. * Creates a disc geometry
  40211. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40212. */
  40213. var DiscGeometry = /** @class */ (function (_super) {
  40214. __extends(DiscGeometry, _super);
  40215. /**
  40216. * Creates a new disc geometry
  40217. * @param id defines the unique ID of the geometry
  40218. * @param scene defines the hosting scene
  40219. * @param radius defines the radius of the disc
  40220. * @param tessellation defines the tesselation factor to apply to the disc
  40221. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40222. * @param mesh defines the hosting mesh (can be null)
  40223. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40224. */
  40225. function DiscGeometry(id, scene,
  40226. /**
  40227. * Defines the radius of the disc
  40228. */
  40229. radius,
  40230. /**
  40231. * Defines the tesselation factor to apply to the disc
  40232. */
  40233. tessellation, canBeRegenerated, mesh,
  40234. /**
  40235. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40236. */
  40237. side) {
  40238. if (mesh === void 0) { mesh = null; }
  40239. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40240. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40241. _this.radius = radius;
  40242. _this.tessellation = tessellation;
  40243. _this.side = side;
  40244. return _this;
  40245. }
  40246. DiscGeometry.prototype._regenerateVertexData = function () {
  40247. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40248. };
  40249. DiscGeometry.prototype.copy = function (id) {
  40250. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40251. };
  40252. return DiscGeometry;
  40253. }(_PrimitiveGeometry));
  40254. BABYLON.DiscGeometry = DiscGeometry;
  40255. /**
  40256. * Creates a new cylinder geometry
  40257. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40258. */
  40259. var CylinderGeometry = /** @class */ (function (_super) {
  40260. __extends(CylinderGeometry, _super);
  40261. /**
  40262. * Creates a new cylinder geometry
  40263. * @param id defines the unique ID of the geometry
  40264. * @param scene defines the hosting scene
  40265. * @param height defines the height of the cylinder
  40266. * @param diameterTop defines the diameter of the cylinder's top cap
  40267. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40268. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40269. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40270. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40271. * @param mesh defines the hosting mesh (can be null)
  40272. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40273. */
  40274. function CylinderGeometry(id, scene,
  40275. /**
  40276. * Defines the height of the cylinder
  40277. */
  40278. height,
  40279. /**
  40280. * Defines the diameter of the cylinder's top cap
  40281. */
  40282. diameterTop,
  40283. /**
  40284. * Defines the diameter of the cylinder's bottom cap
  40285. */
  40286. diameterBottom,
  40287. /**
  40288. * Defines the tessellation factor to apply to the cylinder
  40289. */
  40290. tessellation,
  40291. /**
  40292. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40293. */
  40294. subdivisions, canBeRegenerated, mesh,
  40295. /**
  40296. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40297. */
  40298. side) {
  40299. if (subdivisions === void 0) { subdivisions = 1; }
  40300. if (mesh === void 0) { mesh = null; }
  40301. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40302. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40303. _this.height = height;
  40304. _this.diameterTop = diameterTop;
  40305. _this.diameterBottom = diameterBottom;
  40306. _this.tessellation = tessellation;
  40307. _this.subdivisions = subdivisions;
  40308. _this.side = side;
  40309. return _this;
  40310. }
  40311. CylinderGeometry.prototype._regenerateVertexData = function () {
  40312. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40313. };
  40314. CylinderGeometry.prototype.copy = function (id) {
  40315. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40316. };
  40317. CylinderGeometry.prototype.serialize = function () {
  40318. var serializationObject = _super.prototype.serialize.call(this);
  40319. serializationObject.height = this.height;
  40320. serializationObject.diameterTop = this.diameterTop;
  40321. serializationObject.diameterBottom = this.diameterBottom;
  40322. serializationObject.tessellation = this.tessellation;
  40323. return serializationObject;
  40324. };
  40325. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40326. if (scene.getGeometryByID(parsedCylinder.id)) {
  40327. return null; // null since geometry could be something else than a cylinder...
  40328. }
  40329. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40330. if (BABYLON.Tags) {
  40331. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40332. }
  40333. scene.pushGeometry(cylinder, true);
  40334. return cylinder;
  40335. };
  40336. return CylinderGeometry;
  40337. }(_PrimitiveGeometry));
  40338. BABYLON.CylinderGeometry = CylinderGeometry;
  40339. /**
  40340. * Creates a new torus geometry
  40341. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40342. */
  40343. var TorusGeometry = /** @class */ (function (_super) {
  40344. __extends(TorusGeometry, _super);
  40345. /**
  40346. * Creates a new torus geometry
  40347. * @param id defines the unique ID of the geometry
  40348. * @param scene defines the hosting scene
  40349. * @param diameter defines the diameter of the torus
  40350. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40351. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40352. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40353. * @param mesh defines the hosting mesh (can be null)
  40354. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40355. */
  40356. function TorusGeometry(id, scene,
  40357. /**
  40358. * Defines the diameter of the torus
  40359. */
  40360. diameter,
  40361. /**
  40362. * Defines the thickness of the torus (ie. internal diameter)
  40363. */
  40364. thickness,
  40365. /**
  40366. * Defines the tesselation factor to apply to the torus
  40367. */
  40368. tessellation, canBeRegenerated, mesh,
  40369. /**
  40370. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40371. */
  40372. side) {
  40373. if (mesh === void 0) { mesh = null; }
  40374. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40375. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40376. _this.diameter = diameter;
  40377. _this.thickness = thickness;
  40378. _this.tessellation = tessellation;
  40379. _this.side = side;
  40380. return _this;
  40381. }
  40382. TorusGeometry.prototype._regenerateVertexData = function () {
  40383. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40384. };
  40385. TorusGeometry.prototype.copy = function (id) {
  40386. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40387. };
  40388. TorusGeometry.prototype.serialize = function () {
  40389. var serializationObject = _super.prototype.serialize.call(this);
  40390. serializationObject.diameter = this.diameter;
  40391. serializationObject.thickness = this.thickness;
  40392. serializationObject.tessellation = this.tessellation;
  40393. return serializationObject;
  40394. };
  40395. TorusGeometry.Parse = function (parsedTorus, scene) {
  40396. if (scene.getGeometryByID(parsedTorus.id)) {
  40397. return null; // null since geometry could be something else than a torus...
  40398. }
  40399. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40400. if (BABYLON.Tags) {
  40401. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40402. }
  40403. scene.pushGeometry(torus, true);
  40404. return torus;
  40405. };
  40406. return TorusGeometry;
  40407. }(_PrimitiveGeometry));
  40408. BABYLON.TorusGeometry = TorusGeometry;
  40409. /**
  40410. * Creates a new ground geometry
  40411. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40412. */
  40413. var GroundGeometry = /** @class */ (function (_super) {
  40414. __extends(GroundGeometry, _super);
  40415. /**
  40416. * Creates a new ground geometry
  40417. * @param id defines the unique ID of the geometry
  40418. * @param scene defines the hosting scene
  40419. * @param width defines the width of the ground
  40420. * @param height defines the height of the ground
  40421. * @param subdivisions defines the subdivisions to apply to the ground
  40422. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40423. * @param mesh defines the hosting mesh (can be null)
  40424. */
  40425. function GroundGeometry(id, scene,
  40426. /**
  40427. * Defines the width of the ground
  40428. */
  40429. width,
  40430. /**
  40431. * Defines the height of the ground
  40432. */
  40433. height,
  40434. /**
  40435. * Defines the subdivisions to apply to the ground
  40436. */
  40437. subdivisions, canBeRegenerated, mesh) {
  40438. if (mesh === void 0) { mesh = null; }
  40439. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40440. _this.width = width;
  40441. _this.height = height;
  40442. _this.subdivisions = subdivisions;
  40443. return _this;
  40444. }
  40445. GroundGeometry.prototype._regenerateVertexData = function () {
  40446. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40447. };
  40448. GroundGeometry.prototype.copy = function (id) {
  40449. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40450. };
  40451. GroundGeometry.prototype.serialize = function () {
  40452. var serializationObject = _super.prototype.serialize.call(this);
  40453. serializationObject.width = this.width;
  40454. serializationObject.height = this.height;
  40455. serializationObject.subdivisions = this.subdivisions;
  40456. return serializationObject;
  40457. };
  40458. GroundGeometry.Parse = function (parsedGround, scene) {
  40459. if (scene.getGeometryByID(parsedGround.id)) {
  40460. return null; // null since geometry could be something else than a ground...
  40461. }
  40462. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40463. if (BABYLON.Tags) {
  40464. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40465. }
  40466. scene.pushGeometry(ground, true);
  40467. return ground;
  40468. };
  40469. return GroundGeometry;
  40470. }(_PrimitiveGeometry));
  40471. BABYLON.GroundGeometry = GroundGeometry;
  40472. /**
  40473. * Creates a tiled ground geometry
  40474. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40475. */
  40476. var TiledGroundGeometry = /** @class */ (function (_super) {
  40477. __extends(TiledGroundGeometry, _super);
  40478. /**
  40479. * Creates a tiled ground geometry
  40480. * @param id defines the unique ID of the geometry
  40481. * @param scene defines the hosting scene
  40482. * @param xmin defines the minimum value on X axis
  40483. * @param zmin defines the minimum value on Z axis
  40484. * @param xmax defines the maximum value on X axis
  40485. * @param zmax defines the maximum value on Z axis
  40486. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40487. * @param precision defines the precision to use when computing the tiles
  40488. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40489. * @param mesh defines the hosting mesh (can be null)
  40490. */
  40491. function TiledGroundGeometry(id, scene,
  40492. /**
  40493. * Defines the minimum value on X axis
  40494. */
  40495. xmin,
  40496. /**
  40497. * Defines the minimum value on Z axis
  40498. */
  40499. zmin,
  40500. /**
  40501. * Defines the maximum value on X axis
  40502. */
  40503. xmax,
  40504. /**
  40505. * Defines the maximum value on Z axis
  40506. */
  40507. zmax,
  40508. /**
  40509. * Defines the subdivisions to apply to the ground
  40510. */
  40511. subdivisions,
  40512. /**
  40513. * Defines the precision to use when computing the tiles
  40514. */
  40515. precision, canBeRegenerated, mesh) {
  40516. if (mesh === void 0) { mesh = null; }
  40517. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40518. _this.xmin = xmin;
  40519. _this.zmin = zmin;
  40520. _this.xmax = xmax;
  40521. _this.zmax = zmax;
  40522. _this.subdivisions = subdivisions;
  40523. _this.precision = precision;
  40524. return _this;
  40525. }
  40526. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40527. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40528. };
  40529. TiledGroundGeometry.prototype.copy = function (id) {
  40530. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40531. };
  40532. return TiledGroundGeometry;
  40533. }(_PrimitiveGeometry));
  40534. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40535. /**
  40536. * Creates a plane geometry
  40537. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40538. */
  40539. var PlaneGeometry = /** @class */ (function (_super) {
  40540. __extends(PlaneGeometry, _super);
  40541. /**
  40542. * Creates a plane geometry
  40543. * @param id defines the unique ID of the geometry
  40544. * @param scene defines the hosting scene
  40545. * @param size defines the size of the plane (width === height)
  40546. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40547. * @param mesh defines the hosting mesh (can be null)
  40548. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40549. */
  40550. function PlaneGeometry(id, scene,
  40551. /**
  40552. * Defines the size of the plane (width === height)
  40553. */
  40554. size, canBeRegenerated, mesh,
  40555. /**
  40556. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40557. */
  40558. side) {
  40559. if (mesh === void 0) { mesh = null; }
  40560. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40561. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40562. _this.size = size;
  40563. _this.side = side;
  40564. return _this;
  40565. }
  40566. PlaneGeometry.prototype._regenerateVertexData = function () {
  40567. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40568. };
  40569. PlaneGeometry.prototype.copy = function (id) {
  40570. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40571. };
  40572. PlaneGeometry.prototype.serialize = function () {
  40573. var serializationObject = _super.prototype.serialize.call(this);
  40574. serializationObject.size = this.size;
  40575. return serializationObject;
  40576. };
  40577. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40578. if (scene.getGeometryByID(parsedPlane.id)) {
  40579. return null; // null since geometry could be something else than a ground...
  40580. }
  40581. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40582. if (BABYLON.Tags) {
  40583. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40584. }
  40585. scene.pushGeometry(plane, true);
  40586. return plane;
  40587. };
  40588. return PlaneGeometry;
  40589. }(_PrimitiveGeometry));
  40590. BABYLON.PlaneGeometry = PlaneGeometry;
  40591. /**
  40592. * Creates a torus knot geometry
  40593. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40594. */
  40595. var TorusKnotGeometry = /** @class */ (function (_super) {
  40596. __extends(TorusKnotGeometry, _super);
  40597. /**
  40598. * Creates a torus knot geometry
  40599. * @param id defines the unique ID of the geometry
  40600. * @param scene defines the hosting scene
  40601. * @param radius defines the radius of the torus knot
  40602. * @param tube defines the thickness of the torus knot tube
  40603. * @param radialSegments defines the number of radial segments
  40604. * @param tubularSegments defines the number of tubular segments
  40605. * @param p defines the first number of windings
  40606. * @param q defines the second number of windings
  40607. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40608. * @param mesh defines the hosting mesh (can be null)
  40609. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40610. */
  40611. function TorusKnotGeometry(id, scene,
  40612. /**
  40613. * Defines the radius of the torus knot
  40614. */
  40615. radius,
  40616. /**
  40617. * Defines the thickness of the torus knot tube
  40618. */
  40619. tube,
  40620. /**
  40621. * Defines the number of radial segments
  40622. */
  40623. radialSegments,
  40624. /**
  40625. * Defines the number of tubular segments
  40626. */
  40627. tubularSegments,
  40628. /**
  40629. * Defines the first number of windings
  40630. */
  40631. p,
  40632. /**
  40633. * Defines the second number of windings
  40634. */
  40635. q, canBeRegenerated, mesh,
  40636. /**
  40637. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40638. */
  40639. side) {
  40640. if (mesh === void 0) { mesh = null; }
  40641. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40642. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40643. _this.radius = radius;
  40644. _this.tube = tube;
  40645. _this.radialSegments = radialSegments;
  40646. _this.tubularSegments = tubularSegments;
  40647. _this.p = p;
  40648. _this.q = q;
  40649. _this.side = side;
  40650. return _this;
  40651. }
  40652. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40653. 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 });
  40654. };
  40655. TorusKnotGeometry.prototype.copy = function (id) {
  40656. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40657. };
  40658. TorusKnotGeometry.prototype.serialize = function () {
  40659. var serializationObject = _super.prototype.serialize.call(this);
  40660. serializationObject.radius = this.radius;
  40661. serializationObject.tube = this.tube;
  40662. serializationObject.radialSegments = this.radialSegments;
  40663. serializationObject.tubularSegments = this.tubularSegments;
  40664. serializationObject.p = this.p;
  40665. serializationObject.q = this.q;
  40666. return serializationObject;
  40667. };
  40668. ;
  40669. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40670. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40671. return null; // null since geometry could be something else than a ground...
  40672. }
  40673. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40674. if (BABYLON.Tags) {
  40675. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40676. }
  40677. scene.pushGeometry(torusKnot, true);
  40678. return torusKnot;
  40679. };
  40680. return TorusKnotGeometry;
  40681. }(_PrimitiveGeometry));
  40682. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40683. //}
  40684. })(BABYLON || (BABYLON = {}));
  40685. //# sourceMappingURL=babylon.geometry.js.map
  40686. var BABYLON;
  40687. (function (BABYLON) {
  40688. /**
  40689. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40690. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40691. */
  40692. var PostProcessManager = /** @class */ (function () {
  40693. /**
  40694. * Creates a new instance PostProcess
  40695. * @param scene The scene that the post process is associated with.
  40696. */
  40697. function PostProcessManager(scene) {
  40698. this._vertexBuffers = {};
  40699. this._scene = scene;
  40700. }
  40701. PostProcessManager.prototype._prepareBuffers = function () {
  40702. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40703. return;
  40704. }
  40705. // VBO
  40706. var vertices = [];
  40707. vertices.push(1, 1);
  40708. vertices.push(-1, 1);
  40709. vertices.push(-1, -1);
  40710. vertices.push(1, -1);
  40711. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40712. this._buildIndexBuffer();
  40713. };
  40714. PostProcessManager.prototype._buildIndexBuffer = function () {
  40715. // Indices
  40716. var indices = [];
  40717. indices.push(0);
  40718. indices.push(1);
  40719. indices.push(2);
  40720. indices.push(0);
  40721. indices.push(2);
  40722. indices.push(3);
  40723. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40724. };
  40725. /**
  40726. * Rebuilds the vertex buffers of the manager.
  40727. */
  40728. PostProcessManager.prototype._rebuild = function () {
  40729. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40730. if (!vb) {
  40731. return;
  40732. }
  40733. vb._rebuild();
  40734. this._buildIndexBuffer();
  40735. };
  40736. // Methods
  40737. /**
  40738. * Prepares a frame to be run through a post process.
  40739. * @param sourceTexture The input texture to the post procesess. (default: null)
  40740. * @param postProcesses An array of post processes to be run. (default: null)
  40741. * @returns True if the post processes were able to be run.
  40742. */
  40743. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40744. if (sourceTexture === void 0) { sourceTexture = null; }
  40745. if (postProcesses === void 0) { postProcesses = null; }
  40746. var camera = this._scene.activeCamera;
  40747. if (!camera) {
  40748. return false;
  40749. }
  40750. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40751. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40752. return false;
  40753. }
  40754. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40755. return true;
  40756. };
  40757. /**
  40758. * Manually render a set of post processes to a texture.
  40759. * @param postProcesses An array of post processes to be run.
  40760. * @param targetTexture The target texture to render to.
  40761. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40762. */
  40763. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40764. if (targetTexture === void 0) { targetTexture = null; }
  40765. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40766. var engine = this._scene.getEngine();
  40767. for (var index = 0; index < postProcesses.length; index++) {
  40768. if (index < postProcesses.length - 1) {
  40769. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40770. }
  40771. else {
  40772. if (targetTexture) {
  40773. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40774. }
  40775. else {
  40776. engine.restoreDefaultFramebuffer();
  40777. }
  40778. }
  40779. var pp = postProcesses[index];
  40780. var effect = pp.apply();
  40781. if (effect) {
  40782. pp.onBeforeRenderObservable.notifyObservers(effect);
  40783. // VBOs
  40784. this._prepareBuffers();
  40785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40786. // Draw order
  40787. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40788. pp.onAfterRenderObservable.notifyObservers(effect);
  40789. }
  40790. }
  40791. // Restore depth buffer
  40792. engine.setDepthBuffer(true);
  40793. engine.setDepthWrite(true);
  40794. };
  40795. /**
  40796. * Finalize the result of the output of the postprocesses.
  40797. * @param doNotPresent If true the result will not be displayed to the screen.
  40798. * @param targetTexture The target texture to render to.
  40799. * @param faceIndex The index of the face to bind the target texture to.
  40800. * @param postProcesses The array of post processes to render.
  40801. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40802. */
  40803. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40804. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40805. var camera = this._scene.activeCamera;
  40806. if (!camera) {
  40807. return;
  40808. }
  40809. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40810. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40811. return;
  40812. }
  40813. var engine = this._scene.getEngine();
  40814. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40815. var pp = postProcesses[index];
  40816. if (index < len - 1) {
  40817. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40818. }
  40819. else {
  40820. if (targetTexture) {
  40821. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40822. pp._outputTexture = targetTexture;
  40823. }
  40824. else {
  40825. engine.restoreDefaultFramebuffer();
  40826. pp._outputTexture = null;
  40827. }
  40828. }
  40829. if (doNotPresent) {
  40830. break;
  40831. }
  40832. var effect = pp.apply();
  40833. if (effect) {
  40834. pp.onBeforeRenderObservable.notifyObservers(effect);
  40835. // VBOs
  40836. this._prepareBuffers();
  40837. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40838. // Draw order
  40839. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40840. pp.onAfterRenderObservable.notifyObservers(effect);
  40841. }
  40842. }
  40843. // Restore states
  40844. engine.setDepthBuffer(true);
  40845. engine.setDepthWrite(true);
  40846. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40847. };
  40848. /**
  40849. * Disposes of the post process manager.
  40850. */
  40851. PostProcessManager.prototype.dispose = function () {
  40852. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40853. if (buffer) {
  40854. buffer.dispose();
  40855. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40856. }
  40857. if (this._indexBuffer) {
  40858. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40859. this._indexBuffer = null;
  40860. }
  40861. };
  40862. return PostProcessManager;
  40863. }());
  40864. BABYLON.PostProcessManager = PostProcessManager;
  40865. })(BABYLON || (BABYLON = {}));
  40866. //# sourceMappingURL=babylon.postProcessManager.js.map
  40867. var BABYLON;
  40868. (function (BABYLON) {
  40869. /**
  40870. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40871. */
  40872. var PerformanceMonitor = /** @class */ (function () {
  40873. /**
  40874. * constructor
  40875. * @param frameSampleSize The number of samples required to saturate the sliding window
  40876. */
  40877. function PerformanceMonitor(frameSampleSize) {
  40878. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40879. this._enabled = true;
  40880. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40881. }
  40882. /**
  40883. * Samples current frame
  40884. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40885. */
  40886. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40887. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40888. if (!this._enabled)
  40889. return;
  40890. if (this._lastFrameTimeMs != null) {
  40891. var dt = timeMs - this._lastFrameTimeMs;
  40892. this._rollingFrameTime.add(dt);
  40893. }
  40894. this._lastFrameTimeMs = timeMs;
  40895. };
  40896. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40897. /**
  40898. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40899. * @return Average frame time in milliseconds
  40900. */
  40901. get: function () {
  40902. return this._rollingFrameTime.average;
  40903. },
  40904. enumerable: true,
  40905. configurable: true
  40906. });
  40907. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40908. /**
  40909. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40910. * @return Frame time variance in milliseconds squared
  40911. */
  40912. get: function () {
  40913. return this._rollingFrameTime.variance;
  40914. },
  40915. enumerable: true,
  40916. configurable: true
  40917. });
  40918. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40919. /**
  40920. * Returns the frame time of the most recent frame
  40921. * @return Frame time in milliseconds
  40922. */
  40923. get: function () {
  40924. return this._rollingFrameTime.history(0);
  40925. },
  40926. enumerable: true,
  40927. configurable: true
  40928. });
  40929. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40930. /**
  40931. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40932. * @return Framerate in frames per second
  40933. */
  40934. get: function () {
  40935. return 1000.0 / this._rollingFrameTime.average;
  40936. },
  40937. enumerable: true,
  40938. configurable: true
  40939. });
  40940. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40941. /**
  40942. * Returns the average framerate in frames per second using the most recent frame time
  40943. * @return Framerate in frames per second
  40944. */
  40945. get: function () {
  40946. var history = this._rollingFrameTime.history(0);
  40947. if (history === 0) {
  40948. return 0;
  40949. }
  40950. return 1000.0 / history;
  40951. },
  40952. enumerable: true,
  40953. configurable: true
  40954. });
  40955. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40956. /**
  40957. * Returns true if enough samples have been taken to completely fill the sliding window
  40958. * @return true if saturated
  40959. */
  40960. get: function () {
  40961. return this._rollingFrameTime.isSaturated();
  40962. },
  40963. enumerable: true,
  40964. configurable: true
  40965. });
  40966. /**
  40967. * Enables contributions to the sliding window sample set
  40968. */
  40969. PerformanceMonitor.prototype.enable = function () {
  40970. this._enabled = true;
  40971. };
  40972. /**
  40973. * Disables contributions to the sliding window sample set
  40974. * Samples will not be interpolated over the disabled period
  40975. */
  40976. PerformanceMonitor.prototype.disable = function () {
  40977. this._enabled = false;
  40978. //clear last sample to avoid interpolating over the disabled period when next enabled
  40979. this._lastFrameTimeMs = null;
  40980. };
  40981. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40982. /**
  40983. * Returns true if sampling is enabled
  40984. * @return true if enabled
  40985. */
  40986. get: function () {
  40987. return this._enabled;
  40988. },
  40989. enumerable: true,
  40990. configurable: true
  40991. });
  40992. /**
  40993. * Resets performance monitor
  40994. */
  40995. PerformanceMonitor.prototype.reset = function () {
  40996. //clear last sample to avoid interpolating over the disabled period when next enabled
  40997. this._lastFrameTimeMs = null;
  40998. //wipe record
  40999. this._rollingFrameTime.reset();
  41000. };
  41001. return PerformanceMonitor;
  41002. }());
  41003. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41004. /**
  41005. * RollingAverage
  41006. *
  41007. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41008. */
  41009. var RollingAverage = /** @class */ (function () {
  41010. /**
  41011. * constructor
  41012. * @param length The number of samples required to saturate the sliding window
  41013. */
  41014. function RollingAverage(length) {
  41015. this._samples = new Array(length);
  41016. this.reset();
  41017. }
  41018. /**
  41019. * Adds a sample to the sample set
  41020. * @param v The sample value
  41021. */
  41022. RollingAverage.prototype.add = function (v) {
  41023. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41024. var delta;
  41025. //we need to check if we've already wrapped round
  41026. if (this.isSaturated()) {
  41027. //remove bottom of stack from mean
  41028. var bottomValue = this._samples[this._pos];
  41029. delta = bottomValue - this.average;
  41030. this.average -= delta / (this._sampleCount - 1);
  41031. this._m2 -= delta * (bottomValue - this.average);
  41032. }
  41033. else {
  41034. this._sampleCount++;
  41035. }
  41036. //add new value to mean
  41037. delta = v - this.average;
  41038. this.average += delta / (this._sampleCount);
  41039. this._m2 += delta * (v - this.average);
  41040. //set the new variance
  41041. this.variance = this._m2 / (this._sampleCount - 1);
  41042. this._samples[this._pos] = v;
  41043. this._pos++;
  41044. this._pos %= this._samples.length; //positive wrap around
  41045. };
  41046. /**
  41047. * Returns previously added values or null if outside of history or outside the sliding window domain
  41048. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41049. * @return Value previously recorded with add() or null if outside of range
  41050. */
  41051. RollingAverage.prototype.history = function (i) {
  41052. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41053. return 0;
  41054. }
  41055. var i0 = this._wrapPosition(this._pos - 1.0);
  41056. return this._samples[this._wrapPosition(i0 - i)];
  41057. };
  41058. /**
  41059. * Returns true if enough samples have been taken to completely fill the sliding window
  41060. * @return true if sample-set saturated
  41061. */
  41062. RollingAverage.prototype.isSaturated = function () {
  41063. return this._sampleCount >= this._samples.length;
  41064. };
  41065. /**
  41066. * Resets the rolling average (equivalent to 0 samples taken so far)
  41067. */
  41068. RollingAverage.prototype.reset = function () {
  41069. this.average = 0;
  41070. this.variance = 0;
  41071. this._sampleCount = 0;
  41072. this._pos = 0;
  41073. this._m2 = 0;
  41074. };
  41075. /**
  41076. * Wraps a value around the sample range boundaries
  41077. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41078. * @return Wrapped position in sample range
  41079. */
  41080. RollingAverage.prototype._wrapPosition = function (i) {
  41081. var max = this._samples.length;
  41082. return ((i % max) + max) % max;
  41083. };
  41084. return RollingAverage;
  41085. }());
  41086. BABYLON.RollingAverage = RollingAverage;
  41087. })(BABYLON || (BABYLON = {}));
  41088. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41089. var BABYLON;
  41090. (function (BABYLON) {
  41091. /**
  41092. * This groups together the common properties used for image processing either in direct forward pass
  41093. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41094. * or not.
  41095. */
  41096. var ImageProcessingConfiguration = /** @class */ (function () {
  41097. function ImageProcessingConfiguration() {
  41098. /**
  41099. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41100. */
  41101. this.colorCurves = new BABYLON.ColorCurves();
  41102. this._colorCurvesEnabled = false;
  41103. this._colorGradingEnabled = false;
  41104. this._colorGradingWithGreenDepth = true;
  41105. this._colorGradingBGR = true;
  41106. this._exposure = 1.0;
  41107. this._toneMappingEnabled = false;
  41108. this._contrast = 1.0;
  41109. /**
  41110. * Vignette stretch size.
  41111. */
  41112. this.vignetteStretch = 0;
  41113. /**
  41114. * Vignette centre X Offset.
  41115. */
  41116. this.vignetteCentreX = 0;
  41117. /**
  41118. * Vignette centre Y Offset.
  41119. */
  41120. this.vignetteCentreY = 0;
  41121. /**
  41122. * Vignette weight or intensity of the vignette effect.
  41123. */
  41124. this.vignetteWeight = 1.5;
  41125. /**
  41126. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41127. * if vignetteEnabled is set to true.
  41128. */
  41129. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41130. /**
  41131. * Camera field of view used by the Vignette effect.
  41132. */
  41133. this.vignetteCameraFov = 0.5;
  41134. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41135. this._vignetteEnabled = false;
  41136. this._applyByPostProcess = false;
  41137. this._isEnabled = true;
  41138. /**
  41139. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41140. */
  41141. this.onUpdateParameters = new BABYLON.Observable();
  41142. }
  41143. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41144. /**
  41145. * Gets wether the color curves effect is enabled.
  41146. */
  41147. get: function () {
  41148. return this._colorCurvesEnabled;
  41149. },
  41150. /**
  41151. * Sets wether the color curves effect is enabled.
  41152. */
  41153. set: function (value) {
  41154. if (this._colorCurvesEnabled === value) {
  41155. return;
  41156. }
  41157. this._colorCurvesEnabled = value;
  41158. this._updateParameters();
  41159. },
  41160. enumerable: true,
  41161. configurable: true
  41162. });
  41163. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41164. /**
  41165. * Gets wether the color grading effect is enabled.
  41166. */
  41167. get: function () {
  41168. return this._colorGradingEnabled;
  41169. },
  41170. /**
  41171. * Sets wether the color grading effect is enabled.
  41172. */
  41173. set: function (value) {
  41174. if (this._colorGradingEnabled === value) {
  41175. return;
  41176. }
  41177. this._colorGradingEnabled = value;
  41178. this._updateParameters();
  41179. },
  41180. enumerable: true,
  41181. configurable: true
  41182. });
  41183. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41184. /**
  41185. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41186. */
  41187. get: function () {
  41188. return this._colorGradingWithGreenDepth;
  41189. },
  41190. /**
  41191. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41192. */
  41193. set: function (value) {
  41194. if (this._colorGradingWithGreenDepth === value) {
  41195. return;
  41196. }
  41197. this._colorGradingWithGreenDepth = value;
  41198. this._updateParameters();
  41199. },
  41200. enumerable: true,
  41201. configurable: true
  41202. });
  41203. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41204. /**
  41205. * Gets wether the color grading texture contains BGR values.
  41206. */
  41207. get: function () {
  41208. return this._colorGradingBGR;
  41209. },
  41210. /**
  41211. * Sets wether the color grading texture contains BGR values.
  41212. */
  41213. set: function (value) {
  41214. if (this._colorGradingBGR === value) {
  41215. return;
  41216. }
  41217. this._colorGradingBGR = value;
  41218. this._updateParameters();
  41219. },
  41220. enumerable: true,
  41221. configurable: true
  41222. });
  41223. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41224. /**
  41225. * Gets the Exposure used in the effect.
  41226. */
  41227. get: function () {
  41228. return this._exposure;
  41229. },
  41230. /**
  41231. * Sets the Exposure used in the effect.
  41232. */
  41233. set: function (value) {
  41234. if (this._exposure === value) {
  41235. return;
  41236. }
  41237. this._exposure = value;
  41238. this._updateParameters();
  41239. },
  41240. enumerable: true,
  41241. configurable: true
  41242. });
  41243. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41244. /**
  41245. * Gets wether the tone mapping effect is enabled.
  41246. */
  41247. get: function () {
  41248. return this._toneMappingEnabled;
  41249. },
  41250. /**
  41251. * Sets wether the tone mapping effect is enabled.
  41252. */
  41253. set: function (value) {
  41254. if (this._toneMappingEnabled === value) {
  41255. return;
  41256. }
  41257. this._toneMappingEnabled = value;
  41258. this._updateParameters();
  41259. },
  41260. enumerable: true,
  41261. configurable: true
  41262. });
  41263. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41264. /**
  41265. * Gets the contrast used in the effect.
  41266. */
  41267. get: function () {
  41268. return this._contrast;
  41269. },
  41270. /**
  41271. * Sets the contrast used in the effect.
  41272. */
  41273. set: function (value) {
  41274. if (this._contrast === value) {
  41275. return;
  41276. }
  41277. this._contrast = value;
  41278. this._updateParameters();
  41279. },
  41280. enumerable: true,
  41281. configurable: true
  41282. });
  41283. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41284. /**
  41285. * Gets the vignette blend mode allowing different kind of effect.
  41286. */
  41287. get: function () {
  41288. return this._vignetteBlendMode;
  41289. },
  41290. /**
  41291. * Sets the vignette blend mode allowing different kind of effect.
  41292. */
  41293. set: function (value) {
  41294. if (this._vignetteBlendMode === value) {
  41295. return;
  41296. }
  41297. this._vignetteBlendMode = value;
  41298. this._updateParameters();
  41299. },
  41300. enumerable: true,
  41301. configurable: true
  41302. });
  41303. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41304. /**
  41305. * Gets wether the vignette effect is enabled.
  41306. */
  41307. get: function () {
  41308. return this._vignetteEnabled;
  41309. },
  41310. /**
  41311. * Sets wether the vignette effect is enabled.
  41312. */
  41313. set: function (value) {
  41314. if (this._vignetteEnabled === value) {
  41315. return;
  41316. }
  41317. this._vignetteEnabled = value;
  41318. this._updateParameters();
  41319. },
  41320. enumerable: true,
  41321. configurable: true
  41322. });
  41323. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41324. /**
  41325. * Gets wether the image processing is applied through a post process or not.
  41326. */
  41327. get: function () {
  41328. return this._applyByPostProcess;
  41329. },
  41330. /**
  41331. * Sets wether the image processing is applied through a post process or not.
  41332. */
  41333. set: function (value) {
  41334. if (this._applyByPostProcess === value) {
  41335. return;
  41336. }
  41337. this._applyByPostProcess = value;
  41338. this._updateParameters();
  41339. },
  41340. enumerable: true,
  41341. configurable: true
  41342. });
  41343. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41344. /**
  41345. * Gets wether the image processing is enabled or not.
  41346. */
  41347. get: function () {
  41348. return this._isEnabled;
  41349. },
  41350. /**
  41351. * Sets wether the image processing is enabled or not.
  41352. */
  41353. set: function (value) {
  41354. if (this._isEnabled === value) {
  41355. return;
  41356. }
  41357. this._isEnabled = value;
  41358. this._updateParameters();
  41359. },
  41360. enumerable: true,
  41361. configurable: true
  41362. });
  41363. /**
  41364. * Method called each time the image processing information changes requires to recompile the effect.
  41365. */
  41366. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41367. this.onUpdateParameters.notifyObservers(this);
  41368. };
  41369. ImageProcessingConfiguration.prototype.getClassName = function () {
  41370. return "ImageProcessingConfiguration";
  41371. };
  41372. /**
  41373. * Prepare the list of uniforms associated with the Image Processing effects.
  41374. * @param uniformsList The list of uniforms used in the effect
  41375. * @param defines the list of defines currently in use
  41376. */
  41377. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41378. if (defines.EXPOSURE) {
  41379. uniforms.push("exposureLinear");
  41380. }
  41381. if (defines.CONTRAST) {
  41382. uniforms.push("contrast");
  41383. }
  41384. if (defines.COLORGRADING) {
  41385. uniforms.push("colorTransformSettings");
  41386. }
  41387. if (defines.VIGNETTE) {
  41388. uniforms.push("vInverseScreenSize");
  41389. uniforms.push("vignetteSettings1");
  41390. uniforms.push("vignetteSettings2");
  41391. }
  41392. if (defines.COLORCURVES) {
  41393. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41394. }
  41395. };
  41396. /**
  41397. * Prepare the list of samplers associated with the Image Processing effects.
  41398. * @param uniformsList The list of uniforms used in the effect
  41399. * @param defines the list of defines currently in use
  41400. */
  41401. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41402. if (defines.COLORGRADING) {
  41403. samplersList.push("txColorTransform");
  41404. }
  41405. };
  41406. /**
  41407. * Prepare the list of defines associated to the shader.
  41408. * @param defines the list of defines to complete
  41409. */
  41410. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41411. if (forPostProcess === void 0) { forPostProcess = false; }
  41412. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41413. defines.VIGNETTE = false;
  41414. defines.TONEMAPPING = false;
  41415. defines.CONTRAST = false;
  41416. defines.EXPOSURE = false;
  41417. defines.COLORCURVES = false;
  41418. defines.COLORGRADING = false;
  41419. defines.COLORGRADING3D = false;
  41420. defines.IMAGEPROCESSING = false;
  41421. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41422. return;
  41423. }
  41424. defines.VIGNETTE = this.vignetteEnabled;
  41425. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41426. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41427. defines.TONEMAPPING = this.toneMappingEnabled;
  41428. defines.CONTRAST = (this.contrast !== 1.0);
  41429. defines.EXPOSURE = (this.exposure !== 1.0);
  41430. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41431. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41432. if (defines.COLORGRADING) {
  41433. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41434. }
  41435. else {
  41436. defines.COLORGRADING3D = false;
  41437. }
  41438. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41439. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41440. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41441. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41442. };
  41443. /**
  41444. * Returns true if all the image processing information are ready.
  41445. */
  41446. ImageProcessingConfiguration.prototype.isReady = function () {
  41447. // Color Grading texure can not be none blocking.
  41448. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41449. };
  41450. /**
  41451. * Binds the image processing to the shader.
  41452. * @param effect The effect to bind to
  41453. */
  41454. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41455. if (aspectRatio === void 0) { aspectRatio = 1; }
  41456. // Color Curves
  41457. if (this._colorCurvesEnabled && this.colorCurves) {
  41458. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41459. }
  41460. // Vignette
  41461. if (this._vignetteEnabled) {
  41462. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41463. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41464. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41465. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41466. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41467. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41468. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41469. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41470. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41471. var vignettePower = -2.0 * this.vignetteWeight;
  41472. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41473. }
  41474. // Exposure
  41475. effect.setFloat("exposureLinear", this.exposure);
  41476. // Contrast
  41477. effect.setFloat("contrast", this.contrast);
  41478. // Color transform settings
  41479. if (this.colorGradingTexture) {
  41480. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41481. var textureSize = this.colorGradingTexture.getSize().height;
  41482. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41483. 0.5 / textureSize, // textureOffset
  41484. textureSize, // textureSize
  41485. this.colorGradingTexture.level // weight
  41486. );
  41487. }
  41488. };
  41489. /**
  41490. * Clones the current image processing instance.
  41491. * @return The cloned image processing
  41492. */
  41493. ImageProcessingConfiguration.prototype.clone = function () {
  41494. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41495. };
  41496. /**
  41497. * Serializes the current image processing instance to a json representation.
  41498. * @return a JSON representation
  41499. */
  41500. ImageProcessingConfiguration.prototype.serialize = function () {
  41501. return BABYLON.SerializationHelper.Serialize(this);
  41502. };
  41503. /**
  41504. * Parses the image processing from a json representation.
  41505. * @param source the JSON source to parse
  41506. * @return The parsed image processing
  41507. */
  41508. ImageProcessingConfiguration.Parse = function (source) {
  41509. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41510. };
  41511. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41512. /**
  41513. * Used to apply the vignette as a mix with the pixel color.
  41514. */
  41515. get: function () {
  41516. return this._VIGNETTEMODE_MULTIPLY;
  41517. },
  41518. enumerable: true,
  41519. configurable: true
  41520. });
  41521. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41522. /**
  41523. * Used to apply the vignette as a replacement of the pixel color.
  41524. */
  41525. get: function () {
  41526. return this._VIGNETTEMODE_OPAQUE;
  41527. },
  41528. enumerable: true,
  41529. configurable: true
  41530. });
  41531. // Static constants associated to the image processing.
  41532. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41533. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41534. __decorate([
  41535. BABYLON.serializeAsColorCurves()
  41536. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41537. __decorate([
  41538. BABYLON.serialize()
  41539. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41540. __decorate([
  41541. BABYLON.serializeAsTexture()
  41542. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41543. __decorate([
  41544. BABYLON.serialize()
  41545. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41546. __decorate([
  41547. BABYLON.serialize()
  41548. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41549. __decorate([
  41550. BABYLON.serialize()
  41551. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41552. __decorate([
  41553. BABYLON.serialize()
  41554. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41555. __decorate([
  41556. BABYLON.serialize()
  41557. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41558. __decorate([
  41559. BABYLON.serialize()
  41560. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41561. __decorate([
  41562. BABYLON.serialize()
  41563. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41564. __decorate([
  41565. BABYLON.serialize()
  41566. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41567. __decorate([
  41568. BABYLON.serialize()
  41569. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41570. __decorate([
  41571. BABYLON.serialize()
  41572. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41573. __decorate([
  41574. BABYLON.serializeAsColor4()
  41575. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41576. __decorate([
  41577. BABYLON.serialize()
  41578. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41579. __decorate([
  41580. BABYLON.serialize()
  41581. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41582. __decorate([
  41583. BABYLON.serialize()
  41584. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41585. __decorate([
  41586. BABYLON.serialize()
  41587. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41588. __decorate([
  41589. BABYLON.serialize()
  41590. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41591. return ImageProcessingConfiguration;
  41592. }());
  41593. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41594. })(BABYLON || (BABYLON = {}));
  41595. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41596. var BABYLON;
  41597. (function (BABYLON) {
  41598. /**
  41599. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41600. * It can help converting any input color in a desired output one. This can then be used to create effects
  41601. * from sepia, black and white to sixties or futuristic rendering...
  41602. *
  41603. * The only supported format is currently 3dl.
  41604. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41605. */
  41606. var ColorGradingTexture = /** @class */ (function (_super) {
  41607. __extends(ColorGradingTexture, _super);
  41608. /**
  41609. * Instantiates a ColorGradingTexture from the following parameters.
  41610. *
  41611. * @param url The location of the color gradind data (currently only supporting 3dl)
  41612. * @param scene The scene the texture will be used in
  41613. */
  41614. function ColorGradingTexture(url, scene) {
  41615. var _this = _super.call(this, scene) || this;
  41616. if (!url) {
  41617. return _this;
  41618. }
  41619. _this._engine = scene.getEngine();
  41620. _this._textureMatrix = BABYLON.Matrix.Identity();
  41621. _this.name = url;
  41622. _this.url = url;
  41623. _this.hasAlpha = false;
  41624. _this.isCube = false;
  41625. _this.is3D = _this._engine.webGLVersion > 1;
  41626. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41627. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41628. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41629. _this.anisotropicFilteringLevel = 1;
  41630. _this._texture = _this._getFromCache(url, true);
  41631. if (!_this._texture) {
  41632. if (!scene.useDelayedTextureLoading) {
  41633. _this.loadTexture();
  41634. }
  41635. else {
  41636. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41637. }
  41638. }
  41639. return _this;
  41640. }
  41641. /**
  41642. * Returns the texture matrix used in most of the material.
  41643. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41644. */
  41645. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41646. return this._textureMatrix;
  41647. };
  41648. /**
  41649. * Occurs when the file being loaded is a .3dl LUT file.
  41650. */
  41651. ColorGradingTexture.prototype.load3dlTexture = function () {
  41652. var engine = this._engine;
  41653. var texture;
  41654. if (engine.webGLVersion === 1) {
  41655. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41656. }
  41657. else {
  41658. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41659. }
  41660. this._texture = texture;
  41661. var callback = function (text) {
  41662. if (typeof text !== "string") {
  41663. return;
  41664. }
  41665. var data = null;
  41666. var tempData = null;
  41667. var line;
  41668. var lines = text.split('\n');
  41669. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41670. var maxColor = 0;
  41671. for (var i = 0; i < lines.length; i++) {
  41672. line = lines[i];
  41673. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41674. continue;
  41675. if (line.indexOf('#') === 0)
  41676. continue;
  41677. var words = line.split(" ");
  41678. if (size === 0) {
  41679. // Number of space + one
  41680. size = words.length;
  41681. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41682. tempData = new Float32Array(size * size * size * 4);
  41683. continue;
  41684. }
  41685. if (size != 0) {
  41686. var r = Math.max(parseInt(words[0]), 0);
  41687. var g = Math.max(parseInt(words[1]), 0);
  41688. var b = Math.max(parseInt(words[2]), 0);
  41689. maxColor = Math.max(r, maxColor);
  41690. maxColor = Math.max(g, maxColor);
  41691. maxColor = Math.max(b, maxColor);
  41692. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41693. if (tempData) {
  41694. tempData[pixelStorageIndex + 0] = r;
  41695. tempData[pixelStorageIndex + 1] = g;
  41696. tempData[pixelStorageIndex + 2] = b;
  41697. }
  41698. pixelIndexSlice++;
  41699. if (pixelIndexSlice % size == 0) {
  41700. pixelIndexH++;
  41701. pixelIndexSlice = 0;
  41702. if (pixelIndexH % size == 0) {
  41703. pixelIndexW++;
  41704. pixelIndexH = 0;
  41705. }
  41706. }
  41707. }
  41708. }
  41709. if (tempData && data) {
  41710. for (var i = 0; i < tempData.length; i++) {
  41711. if (i > 0 && (i + 1) % 4 === 0) {
  41712. data[i] = 255;
  41713. }
  41714. else {
  41715. var value = tempData[i];
  41716. data[i] = (value / maxColor * 255);
  41717. }
  41718. }
  41719. }
  41720. if (texture.is3D) {
  41721. texture.updateSize(size, size, size);
  41722. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41723. }
  41724. else {
  41725. texture.updateSize(size * size, size);
  41726. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41727. }
  41728. };
  41729. var scene = this.getScene();
  41730. if (scene) {
  41731. scene._loadFile(this.url, callback);
  41732. }
  41733. else {
  41734. this._engine._loadFile(this.url, callback);
  41735. }
  41736. return this._texture;
  41737. };
  41738. /**
  41739. * Starts the loading process of the texture.
  41740. */
  41741. ColorGradingTexture.prototype.loadTexture = function () {
  41742. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41743. this.load3dlTexture();
  41744. }
  41745. };
  41746. /**
  41747. * Clones the color gradind texture.
  41748. */
  41749. ColorGradingTexture.prototype.clone = function () {
  41750. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41751. // Base texture
  41752. newTexture.level = this.level;
  41753. return newTexture;
  41754. };
  41755. /**
  41756. * Called during delayed load for textures.
  41757. */
  41758. ColorGradingTexture.prototype.delayLoad = function () {
  41759. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41760. return;
  41761. }
  41762. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41763. this._texture = this._getFromCache(this.url, true);
  41764. if (!this._texture) {
  41765. this.loadTexture();
  41766. }
  41767. };
  41768. /**
  41769. * Parses a color grading texture serialized by Babylon.
  41770. * @param parsedTexture The texture information being parsedTexture
  41771. * @param scene The scene to load the texture in
  41772. * @param rootUrl The root url of the data assets to load
  41773. * @return A color gradind texture
  41774. */
  41775. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41776. var texture = null;
  41777. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41778. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41779. texture.name = parsedTexture.name;
  41780. texture.level = parsedTexture.level;
  41781. }
  41782. return texture;
  41783. };
  41784. /**
  41785. * Serializes the LUT texture to json format.
  41786. */
  41787. ColorGradingTexture.prototype.serialize = function () {
  41788. if (!this.name) {
  41789. return null;
  41790. }
  41791. var serializationObject = {};
  41792. serializationObject.name = this.name;
  41793. serializationObject.level = this.level;
  41794. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41795. return serializationObject;
  41796. };
  41797. /**
  41798. * Empty line regex stored for GC.
  41799. */
  41800. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41801. return ColorGradingTexture;
  41802. }(BABYLON.BaseTexture));
  41803. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41804. })(BABYLON || (BABYLON = {}));
  41805. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41806. var BABYLON;
  41807. (function (BABYLON) {
  41808. /**
  41809. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41810. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41811. * 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;
  41812. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41813. */
  41814. var ColorCurves = /** @class */ (function () {
  41815. function ColorCurves() {
  41816. this._dirty = true;
  41817. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41818. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41819. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41820. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41821. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41822. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41823. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41824. this._globalHue = 30;
  41825. this._globalDensity = 0;
  41826. this._globalSaturation = 0;
  41827. this._globalExposure = 0;
  41828. this._highlightsHue = 30;
  41829. this._highlightsDensity = 0;
  41830. this._highlightsSaturation = 0;
  41831. this._highlightsExposure = 0;
  41832. this._midtonesHue = 30;
  41833. this._midtonesDensity = 0;
  41834. this._midtonesSaturation = 0;
  41835. this._midtonesExposure = 0;
  41836. this._shadowsHue = 30;
  41837. this._shadowsDensity = 0;
  41838. this._shadowsSaturation = 0;
  41839. this._shadowsExposure = 0;
  41840. }
  41841. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41842. /**
  41843. * Gets the global Hue value.
  41844. * 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).
  41845. */
  41846. get: function () {
  41847. return this._globalHue;
  41848. },
  41849. /**
  41850. * Sets the global Hue value.
  41851. * 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).
  41852. */
  41853. set: function (value) {
  41854. this._globalHue = value;
  41855. this._dirty = true;
  41856. },
  41857. enumerable: true,
  41858. configurable: true
  41859. });
  41860. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41861. /**
  41862. * Gets the global Density value.
  41863. * 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.
  41864. * Values less than zero provide a filter of opposite hue.
  41865. */
  41866. get: function () {
  41867. return this._globalDensity;
  41868. },
  41869. /**
  41870. * Sets the global Density value.
  41871. * 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.
  41872. * Values less than zero provide a filter of opposite hue.
  41873. */
  41874. set: function (value) {
  41875. this._globalDensity = value;
  41876. this._dirty = true;
  41877. },
  41878. enumerable: true,
  41879. configurable: true
  41880. });
  41881. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41882. /**
  41883. * Gets the global Saturation value.
  41884. * 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.
  41885. */
  41886. get: function () {
  41887. return this._globalSaturation;
  41888. },
  41889. /**
  41890. * Sets the global Saturation value.
  41891. * 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.
  41892. */
  41893. set: function (value) {
  41894. this._globalSaturation = value;
  41895. this._dirty = true;
  41896. },
  41897. enumerable: true,
  41898. configurable: true
  41899. });
  41900. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  41901. /**
  41902. * Gets the global Exposure value.
  41903. * 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.
  41904. */
  41905. get: function () {
  41906. return this._globalExposure;
  41907. },
  41908. /**
  41909. * Sets the global Exposure value.
  41910. * 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.
  41911. */
  41912. set: function (value) {
  41913. this._globalExposure = value;
  41914. this._dirty = true;
  41915. },
  41916. enumerable: true,
  41917. configurable: true
  41918. });
  41919. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41920. /**
  41921. * Gets the highlights Hue value.
  41922. * 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).
  41923. */
  41924. get: function () {
  41925. return this._highlightsHue;
  41926. },
  41927. /**
  41928. * Sets the highlights Hue value.
  41929. * 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).
  41930. */
  41931. set: function (value) {
  41932. this._highlightsHue = value;
  41933. this._dirty = true;
  41934. },
  41935. enumerable: true,
  41936. configurable: true
  41937. });
  41938. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41939. /**
  41940. * Gets the highlights Density value.
  41941. * 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.
  41942. * Values less than zero provide a filter of opposite hue.
  41943. */
  41944. get: function () {
  41945. return this._highlightsDensity;
  41946. },
  41947. /**
  41948. * Sets the highlights Density value.
  41949. * 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.
  41950. * Values less than zero provide a filter of opposite hue.
  41951. */
  41952. set: function (value) {
  41953. this._highlightsDensity = value;
  41954. this._dirty = true;
  41955. },
  41956. enumerable: true,
  41957. configurable: true
  41958. });
  41959. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41960. /**
  41961. * Gets the highlights Saturation value.
  41962. * 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.
  41963. */
  41964. get: function () {
  41965. return this._highlightsSaturation;
  41966. },
  41967. /**
  41968. * Sets the highlights Saturation value.
  41969. * 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.
  41970. */
  41971. set: function (value) {
  41972. this._highlightsSaturation = value;
  41973. this._dirty = true;
  41974. },
  41975. enumerable: true,
  41976. configurable: true
  41977. });
  41978. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41979. /**
  41980. * Gets the highlights Exposure value.
  41981. * 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.
  41982. */
  41983. get: function () {
  41984. return this._highlightsExposure;
  41985. },
  41986. /**
  41987. * Sets the highlights Exposure value.
  41988. * 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.
  41989. */
  41990. set: function (value) {
  41991. this._highlightsExposure = value;
  41992. this._dirty = true;
  41993. },
  41994. enumerable: true,
  41995. configurable: true
  41996. });
  41997. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41998. /**
  41999. * Gets the midtones Hue value.
  42000. * 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).
  42001. */
  42002. get: function () {
  42003. return this._midtonesHue;
  42004. },
  42005. /**
  42006. * Sets the midtones Hue value.
  42007. * 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).
  42008. */
  42009. set: function (value) {
  42010. this._midtonesHue = value;
  42011. this._dirty = true;
  42012. },
  42013. enumerable: true,
  42014. configurable: true
  42015. });
  42016. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42017. /**
  42018. * Gets the midtones Density value.
  42019. * 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.
  42020. * Values less than zero provide a filter of opposite hue.
  42021. */
  42022. get: function () {
  42023. return this._midtonesDensity;
  42024. },
  42025. /**
  42026. * Sets the midtones Density value.
  42027. * 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.
  42028. * Values less than zero provide a filter of opposite hue.
  42029. */
  42030. set: function (value) {
  42031. this._midtonesDensity = value;
  42032. this._dirty = true;
  42033. },
  42034. enumerable: true,
  42035. configurable: true
  42036. });
  42037. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42038. /**
  42039. * Gets the midtones Saturation value.
  42040. * 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.
  42041. */
  42042. get: function () {
  42043. return this._midtonesSaturation;
  42044. },
  42045. /**
  42046. * Sets the midtones Saturation value.
  42047. * 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.
  42048. */
  42049. set: function (value) {
  42050. this._midtonesSaturation = value;
  42051. this._dirty = true;
  42052. },
  42053. enumerable: true,
  42054. configurable: true
  42055. });
  42056. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42057. /**
  42058. * Gets the midtones Exposure value.
  42059. * 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.
  42060. */
  42061. get: function () {
  42062. return this._midtonesExposure;
  42063. },
  42064. /**
  42065. * Sets the midtones Exposure value.
  42066. * 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.
  42067. */
  42068. set: function (value) {
  42069. this._midtonesExposure = value;
  42070. this._dirty = true;
  42071. },
  42072. enumerable: true,
  42073. configurable: true
  42074. });
  42075. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42076. /**
  42077. * Gets the shadows Hue value.
  42078. * 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).
  42079. */
  42080. get: function () {
  42081. return this._shadowsHue;
  42082. },
  42083. /**
  42084. * Sets the shadows Hue value.
  42085. * 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).
  42086. */
  42087. set: function (value) {
  42088. this._shadowsHue = value;
  42089. this._dirty = true;
  42090. },
  42091. enumerable: true,
  42092. configurable: true
  42093. });
  42094. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42095. /**
  42096. * Gets the shadows Density value.
  42097. * 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.
  42098. * Values less than zero provide a filter of opposite hue.
  42099. */
  42100. get: function () {
  42101. return this._shadowsDensity;
  42102. },
  42103. /**
  42104. * Sets the shadows Density value.
  42105. * 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.
  42106. * Values less than zero provide a filter of opposite hue.
  42107. */
  42108. set: function (value) {
  42109. this._shadowsDensity = value;
  42110. this._dirty = true;
  42111. },
  42112. enumerable: true,
  42113. configurable: true
  42114. });
  42115. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42116. /**
  42117. * Gets the shadows Saturation value.
  42118. * 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.
  42119. */
  42120. get: function () {
  42121. return this._shadowsSaturation;
  42122. },
  42123. /**
  42124. * Sets the shadows Saturation value.
  42125. * 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.
  42126. */
  42127. set: function (value) {
  42128. this._shadowsSaturation = value;
  42129. this._dirty = true;
  42130. },
  42131. enumerable: true,
  42132. configurable: true
  42133. });
  42134. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42135. /**
  42136. * Gets the shadows Exposure value.
  42137. * 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.
  42138. */
  42139. get: function () {
  42140. return this._shadowsExposure;
  42141. },
  42142. /**
  42143. * Sets the shadows Exposure value.
  42144. * 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.
  42145. */
  42146. set: function (value) {
  42147. this._shadowsExposure = value;
  42148. this._dirty = true;
  42149. },
  42150. enumerable: true,
  42151. configurable: true
  42152. });
  42153. ColorCurves.prototype.getClassName = function () {
  42154. return "ColorCurves";
  42155. };
  42156. /**
  42157. * Binds the color curves to the shader.
  42158. * @param colorCurves The color curve to bind
  42159. * @param effect The effect to bind to
  42160. */
  42161. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42162. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42163. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42164. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42165. if (colorCurves._dirty) {
  42166. colorCurves._dirty = false;
  42167. // Fill in global info.
  42168. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42169. // Compute highlights info.
  42170. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42171. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42172. // Compute midtones info.
  42173. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42174. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42175. // Compute shadows info.
  42176. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42177. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42178. // Compute deltas (neutral is midtones).
  42179. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42180. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42181. }
  42182. if (effect) {
  42183. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42184. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42185. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42186. }
  42187. };
  42188. /**
  42189. * Prepare the list of uniforms associated with the ColorCurves effects.
  42190. * @param uniformsList The list of uniforms used in the effect
  42191. */
  42192. ColorCurves.PrepareUniforms = function (uniformsList) {
  42193. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42194. };
  42195. /**
  42196. * Returns color grading data based on a hue, density, saturation and exposure value.
  42197. * @param filterHue The hue of the color filter.
  42198. * @param filterDensity The density of the color filter.
  42199. * @param saturation The saturation.
  42200. * @param exposure The exposure.
  42201. * @param result The result data container.
  42202. */
  42203. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42204. if (hue == null) {
  42205. return;
  42206. }
  42207. hue = ColorCurves.clamp(hue, 0, 360);
  42208. density = ColorCurves.clamp(density, -100, 100);
  42209. saturation = ColorCurves.clamp(saturation, -100, 100);
  42210. exposure = ColorCurves.clamp(exposure, -100, 100);
  42211. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42212. // so that the maximum filter density is only 50% control. This provides fine control
  42213. // for small values and reasonable range.
  42214. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42215. density *= 0.5;
  42216. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42217. if (density < 0) {
  42218. density *= -1;
  42219. hue = (hue + 180) % 360;
  42220. }
  42221. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42222. result.scaleToRef(2, result);
  42223. result.a = 1 + 0.01 * saturation;
  42224. };
  42225. /**
  42226. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42227. * @param value The input slider value in range [-100,100].
  42228. * @returns Adjusted value.
  42229. */
  42230. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42231. value /= 100;
  42232. var x = Math.abs(value);
  42233. x = Math.pow(x, 2);
  42234. if (value < 0) {
  42235. x *= -1;
  42236. }
  42237. x *= 100;
  42238. return x;
  42239. };
  42240. /**
  42241. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42242. * @param hue The hue (H) input.
  42243. * @param saturation The saturation (S) input.
  42244. * @param brightness The brightness (B) input.
  42245. * @result An RGBA color represented as Vector4.
  42246. */
  42247. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42248. var h = ColorCurves.clamp(hue, 0, 360);
  42249. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42250. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42251. if (s === 0) {
  42252. result.r = v;
  42253. result.g = v;
  42254. result.b = v;
  42255. }
  42256. else {
  42257. // sector 0 to 5
  42258. h /= 60;
  42259. var i = Math.floor(h);
  42260. // fractional part of h
  42261. var f = h - i;
  42262. var p = v * (1 - s);
  42263. var q = v * (1 - s * f);
  42264. var t = v * (1 - s * (1 - f));
  42265. switch (i) {
  42266. case 0:
  42267. result.r = v;
  42268. result.g = t;
  42269. result.b = p;
  42270. break;
  42271. case 1:
  42272. result.r = q;
  42273. result.g = v;
  42274. result.b = p;
  42275. break;
  42276. case 2:
  42277. result.r = p;
  42278. result.g = v;
  42279. result.b = t;
  42280. break;
  42281. case 3:
  42282. result.r = p;
  42283. result.g = q;
  42284. result.b = v;
  42285. break;
  42286. case 4:
  42287. result.r = t;
  42288. result.g = p;
  42289. result.b = v;
  42290. break;
  42291. default: // case 5:
  42292. result.r = v;
  42293. result.g = p;
  42294. result.b = q;
  42295. break;
  42296. }
  42297. }
  42298. result.a = 1;
  42299. };
  42300. /**
  42301. * Returns a value clamped between min and max
  42302. * @param value The value to clamp
  42303. * @param min The minimum of value
  42304. * @param max The maximum of value
  42305. * @returns The clamped value.
  42306. */
  42307. ColorCurves.clamp = function (value, min, max) {
  42308. return Math.min(Math.max(value, min), max);
  42309. };
  42310. /**
  42311. * Clones the current color curve instance.
  42312. * @return The cloned curves
  42313. */
  42314. ColorCurves.prototype.clone = function () {
  42315. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42316. };
  42317. /**
  42318. * Serializes the current color curve instance to a json representation.
  42319. * @return a JSON representation
  42320. */
  42321. ColorCurves.prototype.serialize = function () {
  42322. return BABYLON.SerializationHelper.Serialize(this);
  42323. };
  42324. /**
  42325. * Parses the color curve from a json representation.
  42326. * @param source the JSON source to parse
  42327. * @return The parsed curves
  42328. */
  42329. ColorCurves.Parse = function (source) {
  42330. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42331. };
  42332. __decorate([
  42333. BABYLON.serialize()
  42334. ], ColorCurves.prototype, "_globalHue", void 0);
  42335. __decorate([
  42336. BABYLON.serialize()
  42337. ], ColorCurves.prototype, "_globalDensity", void 0);
  42338. __decorate([
  42339. BABYLON.serialize()
  42340. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42341. __decorate([
  42342. BABYLON.serialize()
  42343. ], ColorCurves.prototype, "_globalExposure", void 0);
  42344. __decorate([
  42345. BABYLON.serialize()
  42346. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42347. __decorate([
  42348. BABYLON.serialize()
  42349. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42350. __decorate([
  42351. BABYLON.serialize()
  42352. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42353. __decorate([
  42354. BABYLON.serialize()
  42355. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42356. __decorate([
  42357. BABYLON.serialize()
  42358. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42359. __decorate([
  42360. BABYLON.serialize()
  42361. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42362. __decorate([
  42363. BABYLON.serialize()
  42364. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42365. __decorate([
  42366. BABYLON.serialize()
  42367. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42368. return ColorCurves;
  42369. }());
  42370. BABYLON.ColorCurves = ColorCurves;
  42371. })(BABYLON || (BABYLON = {}));
  42372. //# sourceMappingURL=babylon.colorCurves.js.map
  42373. //# sourceMappingURL=babylon.behavior.js.map
  42374. var BABYLON;
  42375. (function (BABYLON) {
  42376. /**
  42377. * "Static Class" containing the most commonly used helper while dealing with material for
  42378. * rendering purpose.
  42379. *
  42380. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42381. *
  42382. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42383. */
  42384. var MaterialHelper = /** @class */ (function () {
  42385. function MaterialHelper() {
  42386. }
  42387. /**
  42388. * Bind the current view position to an effect.
  42389. * @param effect The effect to be bound
  42390. * @param scene The scene the eyes position is used from
  42391. */
  42392. MaterialHelper.BindEyePosition = function (effect, scene) {
  42393. if (scene._forcedViewPosition) {
  42394. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42395. return;
  42396. }
  42397. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42398. };
  42399. /**
  42400. * Helps preparing the defines values about the UVs in used in the effect.
  42401. * UVs are shared as much as we can accross chanels in the shaders.
  42402. * @param texture The texture we are preparing the UVs for
  42403. * @param defines The defines to update
  42404. * @param key The chanel key "diffuse", "specular"... used in the shader
  42405. */
  42406. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42407. defines._needUVs = true;
  42408. defines[key] = true;
  42409. if (texture.getTextureMatrix().isIdentity(true)) {
  42410. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42411. if (texture.coordinatesIndex === 0) {
  42412. defines["MAINUV1"] = true;
  42413. }
  42414. else {
  42415. defines["MAINUV2"] = true;
  42416. }
  42417. }
  42418. else {
  42419. defines[key + "DIRECTUV"] = 0;
  42420. }
  42421. };
  42422. /**
  42423. * Binds a texture matrix value to its corrsponding uniform
  42424. * @param texture The texture to bind the matrix for
  42425. * @param uniformBuffer The uniform buffer receivin the data
  42426. * @param key The chanel key "diffuse", "specular"... used in the shader
  42427. */
  42428. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42429. var matrix = texture.getTextureMatrix();
  42430. if (!matrix.isIdentity(true)) {
  42431. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42432. }
  42433. };
  42434. /**
  42435. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42436. * @param mesh defines the current mesh
  42437. * @param scene defines the current scene
  42438. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42439. * @param pointsCloud defines if point cloud rendering has to be turned on
  42440. * @param fogEnabled defines if fog has to be turned on
  42441. * @param alphaTest defines if alpha testing has to be turned on
  42442. * @param defines defines the current list of defines
  42443. */
  42444. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42445. if (defines._areMiscDirty) {
  42446. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42447. defines["POINTSIZE"] = pointsCloud;
  42448. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42449. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42450. defines["ALPHATEST"] = alphaTest;
  42451. }
  42452. };
  42453. /**
  42454. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42455. * @param scene defines the current scene
  42456. * @param engine defines the current engine
  42457. * @param defines specifies the list of active defines
  42458. * @param useInstances defines if instances have to be turned on
  42459. * @param useClipPlane defines if clip plane have to be turned on
  42460. */
  42461. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42462. if (useClipPlane === void 0) { useClipPlane = null; }
  42463. var changed = false;
  42464. if (useClipPlane == null) {
  42465. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42466. }
  42467. if (defines["CLIPPLANE"] !== useClipPlane) {
  42468. defines["CLIPPLANE"] = useClipPlane;
  42469. changed = true;
  42470. }
  42471. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42472. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42473. changed = true;
  42474. }
  42475. if (defines["INSTANCES"] !== useInstances) {
  42476. defines["INSTANCES"] = useInstances;
  42477. changed = true;
  42478. }
  42479. if (changed) {
  42480. defines.markAsUnprocessed();
  42481. }
  42482. };
  42483. /**
  42484. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42485. * @param mesh The mesh containing the geometry data we will draw
  42486. * @param defines The defines to update
  42487. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42488. * @param useBones Precise whether bones should be used or not (override mesh info)
  42489. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42490. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42491. * @returns false if defines are considered not dirty and have not been checked
  42492. */
  42493. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42494. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42495. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42496. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42497. return false;
  42498. }
  42499. defines._normals = defines._needNormals;
  42500. defines._uvs = defines._needUVs;
  42501. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42502. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42503. defines["TANGENT"] = true;
  42504. }
  42505. if (defines._needUVs) {
  42506. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42507. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42508. }
  42509. else {
  42510. defines["UV1"] = false;
  42511. defines["UV2"] = false;
  42512. }
  42513. if (useVertexColor) {
  42514. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42515. defines["VERTEXCOLOR"] = hasVertexColors;
  42516. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42517. }
  42518. if (useBones) {
  42519. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42520. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42521. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42522. }
  42523. else {
  42524. defines["NUM_BONE_INFLUENCERS"] = 0;
  42525. defines["BonesPerMesh"] = 0;
  42526. }
  42527. }
  42528. if (useMorphTargets) {
  42529. var manager = mesh.morphTargetManager;
  42530. if (manager) {
  42531. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42532. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42533. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42534. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42535. }
  42536. else {
  42537. defines["MORPHTARGETS_TANGENT"] = false;
  42538. defines["MORPHTARGETS_NORMAL"] = false;
  42539. defines["MORPHTARGETS"] = false;
  42540. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42541. }
  42542. }
  42543. return true;
  42544. };
  42545. /**
  42546. * Prepares the defines related to the light information passed in parameter
  42547. * @param scene The scene we are intending to draw
  42548. * @param mesh The mesh the effect is compiling for
  42549. * @param defines The defines to update
  42550. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42551. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42552. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42553. * @returns true if normals will be required for the rest of the effect
  42554. */
  42555. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42556. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42557. if (disableLighting === void 0) { disableLighting = false; }
  42558. if (!defines._areLightsDirty) {
  42559. return defines._needNormals;
  42560. }
  42561. var lightIndex = 0;
  42562. var needNormals = false;
  42563. var needRebuild = false;
  42564. var lightmapMode = false;
  42565. var shadowEnabled = false;
  42566. var specularEnabled = false;
  42567. if (scene.lightsEnabled && !disableLighting) {
  42568. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42569. var light = _a[_i];
  42570. needNormals = true;
  42571. if (defines["LIGHT" + lightIndex] === undefined) {
  42572. needRebuild = true;
  42573. }
  42574. defines["LIGHT" + lightIndex] = true;
  42575. defines["SPOTLIGHT" + lightIndex] = false;
  42576. defines["HEMILIGHT" + lightIndex] = false;
  42577. defines["POINTLIGHT" + lightIndex] = false;
  42578. defines["DIRLIGHT" + lightIndex] = false;
  42579. var type;
  42580. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42581. type = "SPOTLIGHT" + lightIndex;
  42582. var spotLight = light;
  42583. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42584. }
  42585. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42586. type = "HEMILIGHT" + lightIndex;
  42587. }
  42588. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42589. type = "POINTLIGHT" + lightIndex;
  42590. }
  42591. else {
  42592. type = "DIRLIGHT" + lightIndex;
  42593. }
  42594. defines[type] = true;
  42595. // Specular
  42596. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42597. specularEnabled = true;
  42598. }
  42599. // Shadows
  42600. defines["SHADOW" + lightIndex] = false;
  42601. defines["SHADOWPCF" + lightIndex] = false;
  42602. defines["SHADOWPCSS" + lightIndex] = false;
  42603. defines["SHADOWPOISSON" + lightIndex] = false;
  42604. defines["SHADOWESM" + lightIndex] = false;
  42605. defines["SHADOWCUBE" + lightIndex] = false;
  42606. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42607. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42608. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42609. var shadowGenerator = light.getShadowGenerator();
  42610. if (shadowGenerator) {
  42611. shadowEnabled = true;
  42612. shadowGenerator.prepareDefines(defines, lightIndex);
  42613. }
  42614. }
  42615. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42616. lightmapMode = true;
  42617. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42618. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42619. }
  42620. else {
  42621. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42622. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42623. }
  42624. lightIndex++;
  42625. if (lightIndex === maxSimultaneousLights)
  42626. break;
  42627. }
  42628. }
  42629. defines["SPECULARTERM"] = specularEnabled;
  42630. defines["SHADOWS"] = shadowEnabled;
  42631. // Resetting all other lights if any
  42632. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42633. if (defines["LIGHT" + index] !== undefined) {
  42634. defines["LIGHT" + index] = false;
  42635. defines["HEMILIGHT" + lightIndex] = false;
  42636. defines["POINTLIGHT" + lightIndex] = false;
  42637. defines["DIRLIGHT" + lightIndex] = false;
  42638. defines["SPOTLIGHT" + lightIndex] = false;
  42639. defines["SHADOW" + lightIndex] = false;
  42640. }
  42641. }
  42642. var caps = scene.getEngine().getCaps();
  42643. if (defines["SHADOWFLOAT"] === undefined) {
  42644. needRebuild = true;
  42645. }
  42646. defines["SHADOWFLOAT"] = shadowEnabled &&
  42647. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42648. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42649. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42650. if (needRebuild) {
  42651. defines.rebuild();
  42652. }
  42653. return needNormals;
  42654. };
  42655. /**
  42656. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42657. * that won t be acctive due to defines being turned off.
  42658. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42659. * @param samplersList The samplers list
  42660. * @param defines The defines helping in the list generation
  42661. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42662. */
  42663. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42664. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42665. var uniformsList;
  42666. var uniformBuffersList = null;
  42667. if (uniformsListOrOptions.uniformsNames) {
  42668. var options = uniformsListOrOptions;
  42669. uniformsList = options.uniformsNames;
  42670. uniformBuffersList = options.uniformBuffersNames;
  42671. samplersList = options.samplers;
  42672. defines = options.defines;
  42673. maxSimultaneousLights = options.maxSimultaneousLights;
  42674. }
  42675. else {
  42676. uniformsList = uniformsListOrOptions;
  42677. if (!samplersList) {
  42678. samplersList = [];
  42679. }
  42680. }
  42681. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42682. if (!defines["LIGHT" + lightIndex]) {
  42683. break;
  42684. }
  42685. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42686. if (uniformBuffersList) {
  42687. uniformBuffersList.push("Light" + lightIndex);
  42688. }
  42689. samplersList.push("shadowSampler" + lightIndex);
  42690. samplersList.push("depthSampler" + lightIndex);
  42691. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42692. samplersList.push("projectionLightSampler" + lightIndex);
  42693. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42694. }
  42695. }
  42696. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42697. uniformsList.push("morphTargetInfluences");
  42698. }
  42699. };
  42700. /**
  42701. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42702. * @param defines The defines to update while falling back
  42703. * @param fallbacks The authorized effect fallbacks
  42704. * @param maxSimultaneousLights The maximum number of lights allowed
  42705. * @param rank the current rank of the Effect
  42706. * @returns The newly affected rank
  42707. */
  42708. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42709. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42710. if (rank === void 0) { rank = 0; }
  42711. var lightFallbackRank = 0;
  42712. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42713. if (!defines["LIGHT" + lightIndex]) {
  42714. break;
  42715. }
  42716. if (lightIndex > 0) {
  42717. lightFallbackRank = rank + lightIndex;
  42718. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42719. }
  42720. if (!defines["SHADOWS"]) {
  42721. if (defines["SHADOW" + lightIndex]) {
  42722. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42723. }
  42724. if (defines["SHADOWPCF" + lightIndex]) {
  42725. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42726. }
  42727. if (defines["SHADOWPCSS" + lightIndex]) {
  42728. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42729. }
  42730. if (defines["SHADOWPOISSON" + lightIndex]) {
  42731. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42732. }
  42733. if (defines["SHADOWESM" + lightIndex]) {
  42734. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42735. }
  42736. }
  42737. }
  42738. return lightFallbackRank++;
  42739. };
  42740. /**
  42741. * Prepares the list of attributes required for morph targets according to the effect defines.
  42742. * @param attribs The current list of supported attribs
  42743. * @param mesh The mesh to prepare the morph targets attributes for
  42744. * @param defines The current Defines of the effect
  42745. */
  42746. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42747. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42748. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42749. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42750. var manager = mesh.morphTargetManager;
  42751. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42752. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42753. for (var index = 0; index < influencers; index++) {
  42754. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42755. if (normal) {
  42756. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42757. }
  42758. if (tangent) {
  42759. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42760. }
  42761. if (attribs.length > maxAttributesCount) {
  42762. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42763. }
  42764. }
  42765. }
  42766. };
  42767. /**
  42768. * Prepares the list of attributes required for bones according to the effect defines.
  42769. * @param attribs The current list of supported attribs
  42770. * @param mesh The mesh to prepare the bones attributes for
  42771. * @param defines The current Defines of the effect
  42772. * @param fallbacks The current efffect fallback strategy
  42773. */
  42774. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42775. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42776. fallbacks.addCPUSkinningFallback(0, mesh);
  42777. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42778. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42779. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42780. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42781. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42782. }
  42783. }
  42784. };
  42785. /**
  42786. * Prepares the list of attributes required for instances according to the effect defines.
  42787. * @param attribs The current list of supported attribs
  42788. * @param defines The current Defines of the effect
  42789. */
  42790. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42791. if (defines["INSTANCES"]) {
  42792. attribs.push("world0");
  42793. attribs.push("world1");
  42794. attribs.push("world2");
  42795. attribs.push("world3");
  42796. }
  42797. };
  42798. /**
  42799. * Binds the light shadow information to the effect for the given mesh.
  42800. * @param light The light containing the generator
  42801. * @param scene The scene the lights belongs to
  42802. * @param mesh The mesh we are binding the information to render
  42803. * @param lightIndex The light index in the effect used to render the mesh
  42804. * @param effect The effect we are binding the data to
  42805. */
  42806. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42807. if (light.shadowEnabled && mesh.receiveShadows) {
  42808. var shadowGenerator = light.getShadowGenerator();
  42809. if (shadowGenerator) {
  42810. shadowGenerator.bindShadowLight(lightIndex, effect);
  42811. }
  42812. }
  42813. };
  42814. /**
  42815. * Binds the light information to the effect.
  42816. * @param light The light containing the generator
  42817. * @param effect The effect we are binding the data to
  42818. * @param lightIndex The light index in the effect used to render
  42819. */
  42820. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42821. light.transferToEffect(effect, lightIndex + "");
  42822. };
  42823. /**
  42824. * Binds the lights information from the scene to the effect for the given mesh.
  42825. * @param scene The scene the lights belongs to
  42826. * @param mesh The mesh we are binding the information to render
  42827. * @param effect The effect we are binding the data to
  42828. * @param defines The generated defines for the effect
  42829. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42830. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42831. */
  42832. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42833. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42834. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42835. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42836. for (var i = 0; i < len; i++) {
  42837. var light = mesh._lightSources[i];
  42838. var iAsString = i.toString();
  42839. var scaledIntensity = light.getScaledIntensity();
  42840. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42841. MaterialHelper.BindLightProperties(light, effect, i);
  42842. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42843. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42844. if (defines["SPECULARTERM"]) {
  42845. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42846. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42847. }
  42848. // Shadows
  42849. if (scene.shadowsEnabled) {
  42850. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42851. }
  42852. light._uniformBuffer.update();
  42853. }
  42854. };
  42855. /**
  42856. * Binds the fog information from the scene to the effect for the given mesh.
  42857. * @param scene The scene the lights belongs to
  42858. * @param mesh The mesh we are binding the information to render
  42859. * @param effect The effect we are binding the data to
  42860. */
  42861. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42862. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42863. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42864. effect.setColor3("vFogColor", scene.fogColor);
  42865. }
  42866. };
  42867. /**
  42868. * Binds the bones information from the mesh to the effect.
  42869. * @param mesh The mesh we are binding the information to render
  42870. * @param effect The effect we are binding the data to
  42871. */
  42872. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42873. if (!effect || !mesh) {
  42874. return;
  42875. }
  42876. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42877. mesh.computeBonesUsingShaders = false;
  42878. }
  42879. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42880. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42881. if (matrices) {
  42882. effect.setMatrices("mBones", matrices);
  42883. }
  42884. }
  42885. };
  42886. /**
  42887. * Binds the morph targets information from the mesh to the effect.
  42888. * @param abstractMesh The mesh we are binding the information to render
  42889. * @param effect The effect we are binding the data to
  42890. */
  42891. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42892. var manager = abstractMesh.morphTargetManager;
  42893. if (!abstractMesh || !manager) {
  42894. return;
  42895. }
  42896. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42897. };
  42898. /**
  42899. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42900. * @param defines The generated defines used in the effect
  42901. * @param effect The effect we are binding the data to
  42902. * @param scene The scene we are willing to render with logarithmic scale for
  42903. */
  42904. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42905. if (defines["LOGARITHMICDEPTH"]) {
  42906. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42907. }
  42908. };
  42909. /**
  42910. * Binds the clip plane information from the scene to the effect.
  42911. * @param scene The scene the clip plane information are extracted from
  42912. * @param effect The effect we are binding the data to
  42913. */
  42914. MaterialHelper.BindClipPlane = function (effect, scene) {
  42915. if (scene.clipPlane) {
  42916. var clipPlane = scene.clipPlane;
  42917. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42918. }
  42919. };
  42920. return MaterialHelper;
  42921. }());
  42922. BABYLON.MaterialHelper = MaterialHelper;
  42923. })(BABYLON || (BABYLON = {}));
  42924. //# sourceMappingURL=babylon.materialHelper.js.map
  42925. var BABYLON;
  42926. (function (BABYLON) {
  42927. var PushMaterial = /** @class */ (function (_super) {
  42928. __extends(PushMaterial, _super);
  42929. function PushMaterial(name, scene) {
  42930. var _this = _super.call(this, name, scene) || this;
  42931. _this._normalMatrix = new BABYLON.Matrix();
  42932. _this.storeEffectOnSubMeshes = true;
  42933. return _this;
  42934. }
  42935. PushMaterial.prototype.getEffect = function () {
  42936. return this._activeEffect;
  42937. };
  42938. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42939. if (!mesh) {
  42940. return false;
  42941. }
  42942. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42943. return true;
  42944. }
  42945. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42946. };
  42947. /**
  42948. * Binds the given world matrix to the active effect
  42949. *
  42950. * @param world the matrix to bind
  42951. */
  42952. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42953. this._activeEffect.setMatrix("world", world);
  42954. };
  42955. /**
  42956. * Binds the given normal matrix to the active effect
  42957. *
  42958. * @param normalMatrix the matrix to bind
  42959. */
  42960. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42961. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42962. };
  42963. PushMaterial.prototype.bind = function (world, mesh) {
  42964. if (!mesh) {
  42965. return;
  42966. }
  42967. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42968. };
  42969. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42970. if (effect === void 0) { effect = null; }
  42971. _super.prototype._afterBind.call(this, mesh);
  42972. this.getScene()._cachedEffect = effect;
  42973. };
  42974. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42975. if (visibility === void 0) { visibility = 1; }
  42976. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42977. };
  42978. return PushMaterial;
  42979. }(BABYLON.Material));
  42980. BABYLON.PushMaterial = PushMaterial;
  42981. })(BABYLON || (BABYLON = {}));
  42982. //# sourceMappingURL=babylon.pushMaterial.js.map
  42983. var BABYLON;
  42984. (function (BABYLON) {
  42985. /** @hidden */
  42986. var StandardMaterialDefines = /** @class */ (function (_super) {
  42987. __extends(StandardMaterialDefines, _super);
  42988. function StandardMaterialDefines() {
  42989. var _this = _super.call(this) || this;
  42990. _this.MAINUV1 = false;
  42991. _this.MAINUV2 = false;
  42992. _this.DIFFUSE = false;
  42993. _this.DIFFUSEDIRECTUV = 0;
  42994. _this.AMBIENT = false;
  42995. _this.AMBIENTDIRECTUV = 0;
  42996. _this.OPACITY = false;
  42997. _this.OPACITYDIRECTUV = 0;
  42998. _this.OPACITYRGB = false;
  42999. _this.REFLECTION = false;
  43000. _this.EMISSIVE = false;
  43001. _this.EMISSIVEDIRECTUV = 0;
  43002. _this.SPECULAR = false;
  43003. _this.SPECULARDIRECTUV = 0;
  43004. _this.BUMP = false;
  43005. _this.BUMPDIRECTUV = 0;
  43006. _this.PARALLAX = false;
  43007. _this.PARALLAXOCCLUSION = false;
  43008. _this.SPECULAROVERALPHA = false;
  43009. _this.CLIPPLANE = false;
  43010. _this.ALPHATEST = false;
  43011. _this.DEPTHPREPASS = false;
  43012. _this.ALPHAFROMDIFFUSE = false;
  43013. _this.POINTSIZE = false;
  43014. _this.FOG = false;
  43015. _this.SPECULARTERM = false;
  43016. _this.DIFFUSEFRESNEL = false;
  43017. _this.OPACITYFRESNEL = false;
  43018. _this.REFLECTIONFRESNEL = false;
  43019. _this.REFRACTIONFRESNEL = false;
  43020. _this.EMISSIVEFRESNEL = false;
  43021. _this.FRESNEL = false;
  43022. _this.NORMAL = false;
  43023. _this.UV1 = false;
  43024. _this.UV2 = false;
  43025. _this.VERTEXCOLOR = false;
  43026. _this.VERTEXALPHA = false;
  43027. _this.NUM_BONE_INFLUENCERS = 0;
  43028. _this.BonesPerMesh = 0;
  43029. _this.INSTANCES = false;
  43030. _this.GLOSSINESS = false;
  43031. _this.ROUGHNESS = false;
  43032. _this.EMISSIVEASILLUMINATION = false;
  43033. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43034. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43035. _this.LIGHTMAP = false;
  43036. _this.LIGHTMAPDIRECTUV = 0;
  43037. _this.OBJECTSPACE_NORMALMAP = false;
  43038. _this.USELIGHTMAPASSHADOWMAP = false;
  43039. _this.REFLECTIONMAP_3D = false;
  43040. _this.REFLECTIONMAP_SPHERICAL = false;
  43041. _this.REFLECTIONMAP_PLANAR = false;
  43042. _this.REFLECTIONMAP_CUBIC = false;
  43043. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43044. _this.REFLECTIONMAP_PROJECTION = false;
  43045. _this.REFLECTIONMAP_SKYBOX = false;
  43046. _this.REFLECTIONMAP_EXPLICIT = false;
  43047. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43048. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43049. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43050. _this.INVERTCUBICMAP = false;
  43051. _this.LOGARITHMICDEPTH = false;
  43052. _this.REFRACTION = false;
  43053. _this.REFRACTIONMAP_3D = false;
  43054. _this.REFLECTIONOVERALPHA = false;
  43055. _this.TWOSIDEDLIGHTING = false;
  43056. _this.SHADOWFLOAT = false;
  43057. _this.MORPHTARGETS = false;
  43058. _this.MORPHTARGETS_NORMAL = false;
  43059. _this.MORPHTARGETS_TANGENT = false;
  43060. _this.NUM_MORPH_INFLUENCERS = 0;
  43061. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43062. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43063. _this.IMAGEPROCESSING = false;
  43064. _this.VIGNETTE = false;
  43065. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43066. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43067. _this.TONEMAPPING = false;
  43068. _this.CONTRAST = false;
  43069. _this.COLORCURVES = false;
  43070. _this.COLORGRADING = false;
  43071. _this.COLORGRADING3D = false;
  43072. _this.SAMPLER3DGREENDEPTH = false;
  43073. _this.SAMPLER3DBGRMAP = false;
  43074. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43075. /**
  43076. * If the reflection texture on this material is in linear color space
  43077. * @hidden
  43078. */
  43079. _this.IS_REFLECTION_LINEAR = false;
  43080. /**
  43081. * If the refraction texture on this material is in linear color space
  43082. * @hidden
  43083. */
  43084. _this.IS_REFRACTION_LINEAR = false;
  43085. _this.EXPOSURE = false;
  43086. _this.rebuild();
  43087. return _this;
  43088. }
  43089. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43090. var modes = [
  43091. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43092. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43093. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43094. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43095. ];
  43096. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43097. var mode = modes_1[_i];
  43098. this[mode] = (mode === modeToEnable);
  43099. }
  43100. };
  43101. return StandardMaterialDefines;
  43102. }(BABYLON.MaterialDefines));
  43103. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43104. var StandardMaterial = /** @class */ (function (_super) {
  43105. __extends(StandardMaterial, _super);
  43106. function StandardMaterial(name, scene) {
  43107. var _this = _super.call(this, name, scene) || this;
  43108. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43109. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43110. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43111. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43112. _this.specularPower = 64;
  43113. _this._useAlphaFromDiffuseTexture = false;
  43114. _this._useEmissiveAsIllumination = false;
  43115. _this._linkEmissiveWithDiffuse = false;
  43116. _this._useSpecularOverAlpha = false;
  43117. _this._useReflectionOverAlpha = false;
  43118. _this._disableLighting = false;
  43119. _this._useObjectSpaceNormalMap = false;
  43120. _this._useParallax = false;
  43121. _this._useParallaxOcclusion = false;
  43122. _this.parallaxScaleBias = 0.05;
  43123. _this._roughness = 0;
  43124. _this.indexOfRefraction = 0.98;
  43125. _this.invertRefractionY = true;
  43126. /**
  43127. * Defines the alpha limits in alpha test mode
  43128. */
  43129. _this.alphaCutOff = 0.4;
  43130. _this._useLightmapAsShadowmap = false;
  43131. _this._useReflectionFresnelFromSpecular = false;
  43132. _this._useGlossinessFromSpecularMapAlpha = false;
  43133. _this._maxSimultaneousLights = 4;
  43134. /**
  43135. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43136. */
  43137. _this._invertNormalMapX = false;
  43138. /**
  43139. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43140. */
  43141. _this._invertNormalMapY = false;
  43142. /**
  43143. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43144. */
  43145. _this._twoSidedLighting = false;
  43146. _this._renderTargets = new BABYLON.SmartArray(16);
  43147. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43148. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43149. // Setup the default processing configuration to the scene.
  43150. _this._attachImageProcessingConfiguration(null);
  43151. _this.getRenderTargetTextures = function () {
  43152. _this._renderTargets.reset();
  43153. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43154. _this._renderTargets.push(_this._reflectionTexture);
  43155. }
  43156. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43157. _this._renderTargets.push(_this._refractionTexture);
  43158. }
  43159. return _this._renderTargets;
  43160. };
  43161. return _this;
  43162. }
  43163. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43164. /**
  43165. * Gets the image processing configuration used either in this material.
  43166. */
  43167. get: function () {
  43168. return this._imageProcessingConfiguration;
  43169. },
  43170. /**
  43171. * Sets the Default image processing configuration used either in the this material.
  43172. *
  43173. * If sets to null, the scene one is in use.
  43174. */
  43175. set: function (value) {
  43176. this._attachImageProcessingConfiguration(value);
  43177. // Ensure the effect will be rebuilt.
  43178. this._markAllSubMeshesAsTexturesDirty();
  43179. },
  43180. enumerable: true,
  43181. configurable: true
  43182. });
  43183. /**
  43184. * Attaches a new image processing configuration to the Standard Material.
  43185. * @param configuration
  43186. */
  43187. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43188. var _this = this;
  43189. if (configuration === this._imageProcessingConfiguration) {
  43190. return;
  43191. }
  43192. // Detaches observer.
  43193. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43194. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43195. }
  43196. // Pick the scene configuration if needed.
  43197. if (!configuration) {
  43198. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43199. }
  43200. else {
  43201. this._imageProcessingConfiguration = configuration;
  43202. }
  43203. // Attaches observer.
  43204. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43205. _this._markAllSubMeshesAsImageProcessingDirty();
  43206. });
  43207. };
  43208. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43209. /**
  43210. * Gets wether the color curves effect is enabled.
  43211. */
  43212. get: function () {
  43213. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43214. },
  43215. /**
  43216. * Sets wether the color curves effect is enabled.
  43217. */
  43218. set: function (value) {
  43219. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43220. },
  43221. enumerable: true,
  43222. configurable: true
  43223. });
  43224. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43225. /**
  43226. * Gets wether the color grading effect is enabled.
  43227. */
  43228. get: function () {
  43229. return this.imageProcessingConfiguration.colorGradingEnabled;
  43230. },
  43231. /**
  43232. * Gets wether the color grading effect is enabled.
  43233. */
  43234. set: function (value) {
  43235. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43236. },
  43237. enumerable: true,
  43238. configurable: true
  43239. });
  43240. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43241. /**
  43242. * Gets wether tonemapping is enabled or not.
  43243. */
  43244. get: function () {
  43245. return this._imageProcessingConfiguration.toneMappingEnabled;
  43246. },
  43247. /**
  43248. * Sets wether tonemapping is enabled or not
  43249. */
  43250. set: function (value) {
  43251. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43252. },
  43253. enumerable: true,
  43254. configurable: true
  43255. });
  43256. ;
  43257. ;
  43258. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43259. /**
  43260. * The camera exposure used on this material.
  43261. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43262. * This corresponds to a photographic exposure.
  43263. */
  43264. get: function () {
  43265. return this._imageProcessingConfiguration.exposure;
  43266. },
  43267. /**
  43268. * The camera exposure used on this material.
  43269. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43270. * This corresponds to a photographic exposure.
  43271. */
  43272. set: function (value) {
  43273. this._imageProcessingConfiguration.exposure = value;
  43274. },
  43275. enumerable: true,
  43276. configurable: true
  43277. });
  43278. ;
  43279. ;
  43280. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43281. /**
  43282. * Gets The camera contrast used on this material.
  43283. */
  43284. get: function () {
  43285. return this._imageProcessingConfiguration.contrast;
  43286. },
  43287. /**
  43288. * Sets The camera contrast used on this material.
  43289. */
  43290. set: function (value) {
  43291. this._imageProcessingConfiguration.contrast = value;
  43292. },
  43293. enumerable: true,
  43294. configurable: true
  43295. });
  43296. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43297. /**
  43298. * Gets the Color Grading 2D Lookup Texture.
  43299. */
  43300. get: function () {
  43301. return this._imageProcessingConfiguration.colorGradingTexture;
  43302. },
  43303. /**
  43304. * Sets the Color Grading 2D Lookup Texture.
  43305. */
  43306. set: function (value) {
  43307. this._imageProcessingConfiguration.colorGradingTexture = value;
  43308. },
  43309. enumerable: true,
  43310. configurable: true
  43311. });
  43312. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43313. /**
  43314. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43315. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43316. * 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;
  43317. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43318. */
  43319. get: function () {
  43320. return this._imageProcessingConfiguration.colorCurves;
  43321. },
  43322. /**
  43323. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43324. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43325. * 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;
  43326. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43327. */
  43328. set: function (value) {
  43329. this._imageProcessingConfiguration.colorCurves = value;
  43330. },
  43331. enumerable: true,
  43332. configurable: true
  43333. });
  43334. StandardMaterial.prototype.getClassName = function () {
  43335. return "StandardMaterial";
  43336. };
  43337. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43338. get: function () {
  43339. return this._useLogarithmicDepth;
  43340. },
  43341. set: function (value) {
  43342. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43343. this._markAllSubMeshesAsMiscDirty();
  43344. },
  43345. enumerable: true,
  43346. configurable: true
  43347. });
  43348. StandardMaterial.prototype.needAlphaBlending = function () {
  43349. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43350. };
  43351. StandardMaterial.prototype.needAlphaTesting = function () {
  43352. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43353. };
  43354. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43355. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43356. };
  43357. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43358. return this._diffuseTexture;
  43359. };
  43360. /**
  43361. * Child classes can use it to update shaders
  43362. */
  43363. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43364. if (useInstances === void 0) { useInstances = false; }
  43365. if (subMesh.effect && this.isFrozen) {
  43366. if (this._wasPreviouslyReady && subMesh.effect) {
  43367. return true;
  43368. }
  43369. }
  43370. if (!subMesh._materialDefines) {
  43371. subMesh._materialDefines = new StandardMaterialDefines();
  43372. }
  43373. var scene = this.getScene();
  43374. var defines = subMesh._materialDefines;
  43375. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43376. if (defines._renderId === scene.getRenderId()) {
  43377. return true;
  43378. }
  43379. }
  43380. var engine = scene.getEngine();
  43381. // Lights
  43382. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43383. // Textures
  43384. if (defines._areTexturesDirty) {
  43385. defines._needUVs = false;
  43386. defines.MAINUV1 = false;
  43387. defines.MAINUV2 = false;
  43388. if (scene.texturesEnabled) {
  43389. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43390. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43391. return false;
  43392. }
  43393. else {
  43394. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43395. }
  43396. }
  43397. else {
  43398. defines.DIFFUSE = false;
  43399. }
  43400. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43401. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43402. return false;
  43403. }
  43404. else {
  43405. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43406. }
  43407. }
  43408. else {
  43409. defines.AMBIENT = false;
  43410. }
  43411. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43412. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43413. return false;
  43414. }
  43415. else {
  43416. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43417. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43418. }
  43419. }
  43420. else {
  43421. defines.OPACITY = false;
  43422. }
  43423. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43424. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43425. return false;
  43426. }
  43427. else {
  43428. defines._needNormals = true;
  43429. defines.REFLECTION = true;
  43430. defines.ROUGHNESS = (this._roughness > 0);
  43431. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43432. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43433. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43434. switch (this._reflectionTexture.coordinatesMode) {
  43435. case BABYLON.Texture.EXPLICIT_MODE:
  43436. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43437. break;
  43438. case BABYLON.Texture.PLANAR_MODE:
  43439. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43440. break;
  43441. case BABYLON.Texture.PROJECTION_MODE:
  43442. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43443. break;
  43444. case BABYLON.Texture.SKYBOX_MODE:
  43445. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43446. break;
  43447. case BABYLON.Texture.SPHERICAL_MODE:
  43448. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43449. break;
  43450. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43451. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43452. break;
  43453. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43454. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43455. break;
  43456. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43457. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43458. break;
  43459. case BABYLON.Texture.CUBIC_MODE:
  43460. case BABYLON.Texture.INVCUBIC_MODE:
  43461. default:
  43462. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43463. break;
  43464. }
  43465. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43466. }
  43467. }
  43468. else {
  43469. defines.REFLECTION = false;
  43470. }
  43471. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43472. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43473. return false;
  43474. }
  43475. else {
  43476. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43477. }
  43478. }
  43479. else {
  43480. defines.EMISSIVE = false;
  43481. }
  43482. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43483. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43484. return false;
  43485. }
  43486. else {
  43487. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43488. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43489. }
  43490. }
  43491. else {
  43492. defines.LIGHTMAP = false;
  43493. }
  43494. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43495. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43496. return false;
  43497. }
  43498. else {
  43499. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43500. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43501. }
  43502. }
  43503. else {
  43504. defines.SPECULAR = false;
  43505. }
  43506. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43507. // Bump texure can not be not blocking.
  43508. if (!this._bumpTexture.isReady()) {
  43509. return false;
  43510. }
  43511. else {
  43512. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43513. defines.PARALLAX = this._useParallax;
  43514. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43515. }
  43516. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43517. }
  43518. else {
  43519. defines.BUMP = false;
  43520. }
  43521. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43522. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43523. return false;
  43524. }
  43525. else {
  43526. defines._needUVs = true;
  43527. defines.REFRACTION = true;
  43528. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43529. }
  43530. }
  43531. else {
  43532. defines.REFRACTION = false;
  43533. }
  43534. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43535. }
  43536. else {
  43537. defines.DIFFUSE = false;
  43538. defines.AMBIENT = false;
  43539. defines.OPACITY = false;
  43540. defines.REFLECTION = false;
  43541. defines.EMISSIVE = false;
  43542. defines.LIGHTMAP = false;
  43543. defines.BUMP = false;
  43544. defines.REFRACTION = false;
  43545. }
  43546. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43547. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43548. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43549. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43550. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43551. }
  43552. if (defines._areImageProcessingDirty) {
  43553. if (!this._imageProcessingConfiguration.isReady()) {
  43554. return false;
  43555. }
  43556. this._imageProcessingConfiguration.prepareDefines(defines);
  43557. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43558. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43559. }
  43560. if (defines._areFresnelDirty) {
  43561. if (StandardMaterial.FresnelEnabled) {
  43562. // Fresnel
  43563. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43564. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43565. this._reflectionFresnelParameters) {
  43566. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43567. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43568. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43569. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43570. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43571. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43572. defines._needNormals = true;
  43573. defines.FRESNEL = true;
  43574. }
  43575. }
  43576. else {
  43577. defines.FRESNEL = false;
  43578. }
  43579. }
  43580. // Misc.
  43581. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43582. // Attribs
  43583. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43584. // Values that need to be evaluated on every frame
  43585. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43586. // Get correct effect
  43587. if (defines.isDirty) {
  43588. defines.markAsProcessed();
  43589. scene.resetCachedMaterial();
  43590. // Fallbacks
  43591. var fallbacks = new BABYLON.EffectFallbacks();
  43592. if (defines.REFLECTION) {
  43593. fallbacks.addFallback(0, "REFLECTION");
  43594. }
  43595. if (defines.SPECULAR) {
  43596. fallbacks.addFallback(0, "SPECULAR");
  43597. }
  43598. if (defines.BUMP) {
  43599. fallbacks.addFallback(0, "BUMP");
  43600. }
  43601. if (defines.PARALLAX) {
  43602. fallbacks.addFallback(1, "PARALLAX");
  43603. }
  43604. if (defines.PARALLAXOCCLUSION) {
  43605. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43606. }
  43607. if (defines.SPECULAROVERALPHA) {
  43608. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43609. }
  43610. if (defines.FOG) {
  43611. fallbacks.addFallback(1, "FOG");
  43612. }
  43613. if (defines.POINTSIZE) {
  43614. fallbacks.addFallback(0, "POINTSIZE");
  43615. }
  43616. if (defines.LOGARITHMICDEPTH) {
  43617. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43618. }
  43619. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43620. if (defines.SPECULARTERM) {
  43621. fallbacks.addFallback(0, "SPECULARTERM");
  43622. }
  43623. if (defines.DIFFUSEFRESNEL) {
  43624. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43625. }
  43626. if (defines.OPACITYFRESNEL) {
  43627. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43628. }
  43629. if (defines.REFLECTIONFRESNEL) {
  43630. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43631. }
  43632. if (defines.EMISSIVEFRESNEL) {
  43633. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43634. }
  43635. if (defines.FRESNEL) {
  43636. fallbacks.addFallback(4, "FRESNEL");
  43637. }
  43638. //Attributes
  43639. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43640. if (defines.NORMAL) {
  43641. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43642. }
  43643. if (defines.UV1) {
  43644. attribs.push(BABYLON.VertexBuffer.UVKind);
  43645. }
  43646. if (defines.UV2) {
  43647. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43648. }
  43649. if (defines.VERTEXCOLOR) {
  43650. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43651. }
  43652. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43653. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43654. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43655. var shaderName = "default";
  43656. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43657. "vFogInfos", "vFogColor", "pointSize",
  43658. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43659. "mBones",
  43660. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43661. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43662. "vReflectionPosition", "vReflectionSize",
  43663. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43664. ];
  43665. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43666. var uniformBuffers = ["Material", "Scene"];
  43667. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43668. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43669. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43670. uniformsNames: uniforms,
  43671. uniformBuffersNames: uniformBuffers,
  43672. samplers: samplers,
  43673. defines: defines,
  43674. maxSimultaneousLights: this._maxSimultaneousLights
  43675. });
  43676. if (this.customShaderNameResolve) {
  43677. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43678. }
  43679. var join = defines.toString();
  43680. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43681. attributes: attribs,
  43682. uniformsNames: uniforms,
  43683. uniformBuffersNames: uniformBuffers,
  43684. samplers: samplers,
  43685. defines: join,
  43686. fallbacks: fallbacks,
  43687. onCompiled: this.onCompiled,
  43688. onError: this.onError,
  43689. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43690. }, engine), defines);
  43691. this.buildUniformLayout();
  43692. }
  43693. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43694. return false;
  43695. }
  43696. defines._renderId = scene.getRenderId();
  43697. this._wasPreviouslyReady = true;
  43698. return true;
  43699. };
  43700. StandardMaterial.prototype.buildUniformLayout = function () {
  43701. // Order is important !
  43702. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43703. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43704. this._uniformBuffer.addUniform("opacityParts", 4);
  43705. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43706. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43707. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43708. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43709. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43710. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43711. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43712. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43713. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43714. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43715. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43716. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43717. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43718. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43719. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43720. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43721. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43722. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43723. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43724. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43725. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43726. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43727. this._uniformBuffer.addUniform("specularMatrix", 16);
  43728. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43729. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43730. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43731. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43732. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43733. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43734. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43735. this._uniformBuffer.addUniform("pointSize", 1);
  43736. this._uniformBuffer.create();
  43737. };
  43738. StandardMaterial.prototype.unbind = function () {
  43739. if (this._activeEffect) {
  43740. var needFlag = false;
  43741. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43742. this._activeEffect.setTexture("reflection2DSampler", null);
  43743. needFlag = true;
  43744. }
  43745. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43746. this._activeEffect.setTexture("refraction2DSampler", null);
  43747. needFlag = true;
  43748. }
  43749. if (needFlag) {
  43750. this._markAllSubMeshesAsTexturesDirty();
  43751. }
  43752. }
  43753. _super.prototype.unbind.call(this);
  43754. };
  43755. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43756. var scene = this.getScene();
  43757. var defines = subMesh._materialDefines;
  43758. if (!defines) {
  43759. return;
  43760. }
  43761. var effect = subMesh.effect;
  43762. if (!effect) {
  43763. return;
  43764. }
  43765. this._activeEffect = effect;
  43766. // Matrices
  43767. this.bindOnlyWorldMatrix(world);
  43768. // Normal Matrix
  43769. if (defines.OBJECTSPACE_NORMALMAP) {
  43770. world.toNormalMatrix(this._normalMatrix);
  43771. this.bindOnlyNormalMatrix(this._normalMatrix);
  43772. }
  43773. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43774. // Bones
  43775. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43776. if (mustRebind) {
  43777. this._uniformBuffer.bindToEffect(effect, "Material");
  43778. this.bindViewProjection(effect);
  43779. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43780. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43781. // Fresnel
  43782. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43783. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43784. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43785. }
  43786. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43787. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43788. }
  43789. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43790. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43791. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43792. }
  43793. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43794. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43795. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43796. }
  43797. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43798. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43799. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43800. }
  43801. }
  43802. // Textures
  43803. if (scene.texturesEnabled) {
  43804. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43805. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43806. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43807. if (this._diffuseTexture.hasAlpha) {
  43808. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43809. }
  43810. }
  43811. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43812. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43813. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43814. }
  43815. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43816. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43817. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43818. }
  43819. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43820. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43821. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43822. if (this._reflectionTexture.boundingBoxSize) {
  43823. var cubeTexture = this._reflectionTexture;
  43824. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43825. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43826. }
  43827. }
  43828. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43829. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43830. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43831. }
  43832. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43833. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43834. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43835. }
  43836. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43837. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43838. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43839. }
  43840. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43841. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43842. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43843. if (scene._mirroredCameraPosition) {
  43844. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43845. }
  43846. else {
  43847. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43848. }
  43849. }
  43850. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43851. var depth = 1.0;
  43852. if (!this._refractionTexture.isCube) {
  43853. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43854. if (this._refractionTexture.depth) {
  43855. depth = this._refractionTexture.depth;
  43856. }
  43857. }
  43858. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43859. }
  43860. }
  43861. // Point size
  43862. if (this.pointsCloud) {
  43863. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43864. }
  43865. if (defines.SPECULARTERM) {
  43866. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43867. }
  43868. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43869. // Diffuse
  43870. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43871. }
  43872. // Textures
  43873. if (scene.texturesEnabled) {
  43874. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43875. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43876. }
  43877. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43878. effect.setTexture("ambientSampler", this._ambientTexture);
  43879. }
  43880. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43881. effect.setTexture("opacitySampler", this._opacityTexture);
  43882. }
  43883. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43884. if (this._reflectionTexture.isCube) {
  43885. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43886. }
  43887. else {
  43888. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43889. }
  43890. }
  43891. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43892. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43893. }
  43894. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43895. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43896. }
  43897. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43898. effect.setTexture("specularSampler", this._specularTexture);
  43899. }
  43900. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43901. effect.setTexture("bumpSampler", this._bumpTexture);
  43902. }
  43903. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43904. var depth = 1.0;
  43905. if (this._refractionTexture.isCube) {
  43906. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43907. }
  43908. else {
  43909. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43910. }
  43911. }
  43912. }
  43913. // Clip plane
  43914. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43915. // Colors
  43916. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43917. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43918. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43919. }
  43920. if (mustRebind || !this.isFrozen) {
  43921. // Lights
  43922. if (scene.lightsEnabled && !this._disableLighting) {
  43923. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43924. }
  43925. // View
  43926. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43927. this.bindView(effect);
  43928. }
  43929. // Fog
  43930. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43931. // Morph targets
  43932. if (defines.NUM_MORPH_INFLUENCERS) {
  43933. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43934. }
  43935. // Log. depth
  43936. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43937. // image processing
  43938. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43939. this._imageProcessingConfiguration.bind(this._activeEffect);
  43940. }
  43941. }
  43942. this._uniformBuffer.update();
  43943. this._afterBind(mesh, this._activeEffect);
  43944. };
  43945. StandardMaterial.prototype.getAnimatables = function () {
  43946. var results = [];
  43947. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43948. results.push(this._diffuseTexture);
  43949. }
  43950. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43951. results.push(this._ambientTexture);
  43952. }
  43953. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43954. results.push(this._opacityTexture);
  43955. }
  43956. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43957. results.push(this._reflectionTexture);
  43958. }
  43959. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43960. results.push(this._emissiveTexture);
  43961. }
  43962. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43963. results.push(this._specularTexture);
  43964. }
  43965. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43966. results.push(this._bumpTexture);
  43967. }
  43968. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43969. results.push(this._lightmapTexture);
  43970. }
  43971. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43972. results.push(this._refractionTexture);
  43973. }
  43974. return results;
  43975. };
  43976. StandardMaterial.prototype.getActiveTextures = function () {
  43977. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43978. if (this._diffuseTexture) {
  43979. activeTextures.push(this._diffuseTexture);
  43980. }
  43981. if (this._ambientTexture) {
  43982. activeTextures.push(this._ambientTexture);
  43983. }
  43984. if (this._opacityTexture) {
  43985. activeTextures.push(this._opacityTexture);
  43986. }
  43987. if (this._reflectionTexture) {
  43988. activeTextures.push(this._reflectionTexture);
  43989. }
  43990. if (this._emissiveTexture) {
  43991. activeTextures.push(this._emissiveTexture);
  43992. }
  43993. if (this._specularTexture) {
  43994. activeTextures.push(this._specularTexture);
  43995. }
  43996. if (this._bumpTexture) {
  43997. activeTextures.push(this._bumpTexture);
  43998. }
  43999. if (this._lightmapTexture) {
  44000. activeTextures.push(this._lightmapTexture);
  44001. }
  44002. if (this._refractionTexture) {
  44003. activeTextures.push(this._refractionTexture);
  44004. }
  44005. return activeTextures;
  44006. };
  44007. StandardMaterial.prototype.hasTexture = function (texture) {
  44008. if (_super.prototype.hasTexture.call(this, texture)) {
  44009. return true;
  44010. }
  44011. if (this._diffuseTexture === texture) {
  44012. return true;
  44013. }
  44014. if (this._ambientTexture === texture) {
  44015. return true;
  44016. }
  44017. if (this._opacityTexture === texture) {
  44018. return true;
  44019. }
  44020. if (this._reflectionTexture === texture) {
  44021. return true;
  44022. }
  44023. if (this._emissiveTexture === texture) {
  44024. return true;
  44025. }
  44026. if (this._specularTexture === texture) {
  44027. return true;
  44028. }
  44029. if (this._bumpTexture === texture) {
  44030. return true;
  44031. }
  44032. if (this._lightmapTexture === texture) {
  44033. return true;
  44034. }
  44035. if (this._refractionTexture === texture) {
  44036. return true;
  44037. }
  44038. return false;
  44039. };
  44040. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44041. if (forceDisposeTextures) {
  44042. if (this._diffuseTexture) {
  44043. this._diffuseTexture.dispose();
  44044. }
  44045. if (this._ambientTexture) {
  44046. this._ambientTexture.dispose();
  44047. }
  44048. if (this._opacityTexture) {
  44049. this._opacityTexture.dispose();
  44050. }
  44051. if (this._reflectionTexture) {
  44052. this._reflectionTexture.dispose();
  44053. }
  44054. if (this._emissiveTexture) {
  44055. this._emissiveTexture.dispose();
  44056. }
  44057. if (this._specularTexture) {
  44058. this._specularTexture.dispose();
  44059. }
  44060. if (this._bumpTexture) {
  44061. this._bumpTexture.dispose();
  44062. }
  44063. if (this._lightmapTexture) {
  44064. this._lightmapTexture.dispose();
  44065. }
  44066. if (this._refractionTexture) {
  44067. this._refractionTexture.dispose();
  44068. }
  44069. }
  44070. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44071. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44072. }
  44073. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44074. };
  44075. StandardMaterial.prototype.clone = function (name) {
  44076. var _this = this;
  44077. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44078. result.name = name;
  44079. result.id = name;
  44080. return result;
  44081. };
  44082. StandardMaterial.prototype.serialize = function () {
  44083. return BABYLON.SerializationHelper.Serialize(this);
  44084. };
  44085. // Statics
  44086. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44087. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44088. };
  44089. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44090. get: function () {
  44091. return StandardMaterial._DiffuseTextureEnabled;
  44092. },
  44093. set: function (value) {
  44094. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44095. return;
  44096. }
  44097. StandardMaterial._DiffuseTextureEnabled = value;
  44098. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44099. },
  44100. enumerable: true,
  44101. configurable: true
  44102. });
  44103. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44104. get: function () {
  44105. return StandardMaterial._AmbientTextureEnabled;
  44106. },
  44107. set: function (value) {
  44108. if (StandardMaterial._AmbientTextureEnabled === value) {
  44109. return;
  44110. }
  44111. StandardMaterial._AmbientTextureEnabled = value;
  44112. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44113. },
  44114. enumerable: true,
  44115. configurable: true
  44116. });
  44117. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44118. get: function () {
  44119. return StandardMaterial._OpacityTextureEnabled;
  44120. },
  44121. set: function (value) {
  44122. if (StandardMaterial._OpacityTextureEnabled === value) {
  44123. return;
  44124. }
  44125. StandardMaterial._OpacityTextureEnabled = value;
  44126. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44127. },
  44128. enumerable: true,
  44129. configurable: true
  44130. });
  44131. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44132. get: function () {
  44133. return StandardMaterial._ReflectionTextureEnabled;
  44134. },
  44135. set: function (value) {
  44136. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44137. return;
  44138. }
  44139. StandardMaterial._ReflectionTextureEnabled = value;
  44140. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44141. },
  44142. enumerable: true,
  44143. configurable: true
  44144. });
  44145. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44146. get: function () {
  44147. return StandardMaterial._EmissiveTextureEnabled;
  44148. },
  44149. set: function (value) {
  44150. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44151. return;
  44152. }
  44153. StandardMaterial._EmissiveTextureEnabled = value;
  44154. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44155. },
  44156. enumerable: true,
  44157. configurable: true
  44158. });
  44159. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44160. get: function () {
  44161. return StandardMaterial._SpecularTextureEnabled;
  44162. },
  44163. set: function (value) {
  44164. if (StandardMaterial._SpecularTextureEnabled === value) {
  44165. return;
  44166. }
  44167. StandardMaterial._SpecularTextureEnabled = value;
  44168. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44169. },
  44170. enumerable: true,
  44171. configurable: true
  44172. });
  44173. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44174. get: function () {
  44175. return StandardMaterial._BumpTextureEnabled;
  44176. },
  44177. set: function (value) {
  44178. if (StandardMaterial._BumpTextureEnabled === value) {
  44179. return;
  44180. }
  44181. StandardMaterial._BumpTextureEnabled = value;
  44182. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44183. },
  44184. enumerable: true,
  44185. configurable: true
  44186. });
  44187. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44188. get: function () {
  44189. return StandardMaterial._LightmapTextureEnabled;
  44190. },
  44191. set: function (value) {
  44192. if (StandardMaterial._LightmapTextureEnabled === value) {
  44193. return;
  44194. }
  44195. StandardMaterial._LightmapTextureEnabled = value;
  44196. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44197. },
  44198. enumerable: true,
  44199. configurable: true
  44200. });
  44201. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44202. get: function () {
  44203. return StandardMaterial._RefractionTextureEnabled;
  44204. },
  44205. set: function (value) {
  44206. if (StandardMaterial._RefractionTextureEnabled === value) {
  44207. return;
  44208. }
  44209. StandardMaterial._RefractionTextureEnabled = value;
  44210. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44211. },
  44212. enumerable: true,
  44213. configurable: true
  44214. });
  44215. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44216. get: function () {
  44217. return StandardMaterial._ColorGradingTextureEnabled;
  44218. },
  44219. set: function (value) {
  44220. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44221. return;
  44222. }
  44223. StandardMaterial._ColorGradingTextureEnabled = value;
  44224. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44225. },
  44226. enumerable: true,
  44227. configurable: true
  44228. });
  44229. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44230. get: function () {
  44231. return StandardMaterial._FresnelEnabled;
  44232. },
  44233. set: function (value) {
  44234. if (StandardMaterial._FresnelEnabled === value) {
  44235. return;
  44236. }
  44237. StandardMaterial._FresnelEnabled = value;
  44238. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44239. },
  44240. enumerable: true,
  44241. configurable: true
  44242. });
  44243. // Flags used to enable or disable a type of texture for all Standard Materials
  44244. StandardMaterial._DiffuseTextureEnabled = true;
  44245. StandardMaterial._AmbientTextureEnabled = true;
  44246. StandardMaterial._OpacityTextureEnabled = true;
  44247. StandardMaterial._ReflectionTextureEnabled = true;
  44248. StandardMaterial._EmissiveTextureEnabled = true;
  44249. StandardMaterial._SpecularTextureEnabled = true;
  44250. StandardMaterial._BumpTextureEnabled = true;
  44251. StandardMaterial._LightmapTextureEnabled = true;
  44252. StandardMaterial._RefractionTextureEnabled = true;
  44253. StandardMaterial._ColorGradingTextureEnabled = true;
  44254. StandardMaterial._FresnelEnabled = true;
  44255. __decorate([
  44256. BABYLON.serializeAsTexture("diffuseTexture")
  44257. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44258. __decorate([
  44259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44260. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44261. __decorate([
  44262. BABYLON.serializeAsTexture("ambientTexture")
  44263. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44264. __decorate([
  44265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44266. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44267. __decorate([
  44268. BABYLON.serializeAsTexture("opacityTexture")
  44269. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44270. __decorate([
  44271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44272. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44273. __decorate([
  44274. BABYLON.serializeAsTexture("reflectionTexture")
  44275. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44276. __decorate([
  44277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44278. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44279. __decorate([
  44280. BABYLON.serializeAsTexture("emissiveTexture")
  44281. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44282. __decorate([
  44283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44284. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44285. __decorate([
  44286. BABYLON.serializeAsTexture("specularTexture")
  44287. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44288. __decorate([
  44289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44290. ], StandardMaterial.prototype, "specularTexture", void 0);
  44291. __decorate([
  44292. BABYLON.serializeAsTexture("bumpTexture")
  44293. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44294. __decorate([
  44295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44296. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44297. __decorate([
  44298. BABYLON.serializeAsTexture("lightmapTexture")
  44299. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44300. __decorate([
  44301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44302. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44303. __decorate([
  44304. BABYLON.serializeAsTexture("refractionTexture")
  44305. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44306. __decorate([
  44307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44308. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44309. __decorate([
  44310. BABYLON.serializeAsColor3("ambient")
  44311. ], StandardMaterial.prototype, "ambientColor", void 0);
  44312. __decorate([
  44313. BABYLON.serializeAsColor3("diffuse")
  44314. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44315. __decorate([
  44316. BABYLON.serializeAsColor3("specular")
  44317. ], StandardMaterial.prototype, "specularColor", void 0);
  44318. __decorate([
  44319. BABYLON.serializeAsColor3("emissive")
  44320. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44321. __decorate([
  44322. BABYLON.serialize()
  44323. ], StandardMaterial.prototype, "specularPower", void 0);
  44324. __decorate([
  44325. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44326. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44327. __decorate([
  44328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44329. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44330. __decorate([
  44331. BABYLON.serialize("useEmissiveAsIllumination")
  44332. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44333. __decorate([
  44334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44335. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44336. __decorate([
  44337. BABYLON.serialize("linkEmissiveWithDiffuse")
  44338. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44339. __decorate([
  44340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44341. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44342. __decorate([
  44343. BABYLON.serialize("useSpecularOverAlpha")
  44344. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44345. __decorate([
  44346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44347. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44348. __decorate([
  44349. BABYLON.serialize("useReflectionOverAlpha")
  44350. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44351. __decorate([
  44352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44353. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44354. __decorate([
  44355. BABYLON.serialize("disableLighting")
  44356. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44357. __decorate([
  44358. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44359. ], StandardMaterial.prototype, "disableLighting", void 0);
  44360. __decorate([
  44361. BABYLON.serialize("useObjectSpaceNormalMap")
  44362. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44363. __decorate([
  44364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44365. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44366. __decorate([
  44367. BABYLON.serialize("useParallax")
  44368. ], StandardMaterial.prototype, "_useParallax", void 0);
  44369. __decorate([
  44370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44371. ], StandardMaterial.prototype, "useParallax", void 0);
  44372. __decorate([
  44373. BABYLON.serialize("useParallaxOcclusion")
  44374. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44375. __decorate([
  44376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44377. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44378. __decorate([
  44379. BABYLON.serialize()
  44380. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44381. __decorate([
  44382. BABYLON.serialize("roughness")
  44383. ], StandardMaterial.prototype, "_roughness", void 0);
  44384. __decorate([
  44385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44386. ], StandardMaterial.prototype, "roughness", void 0);
  44387. __decorate([
  44388. BABYLON.serialize()
  44389. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44390. __decorate([
  44391. BABYLON.serialize()
  44392. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44393. __decorate([
  44394. BABYLON.serialize()
  44395. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44396. __decorate([
  44397. BABYLON.serialize("useLightmapAsShadowmap")
  44398. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44399. __decorate([
  44400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44401. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44402. __decorate([
  44403. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44404. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44405. __decorate([
  44406. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44407. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44408. __decorate([
  44409. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44410. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44411. __decorate([
  44412. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44413. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44414. __decorate([
  44415. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44416. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44417. __decorate([
  44418. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44419. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44420. __decorate([
  44421. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44422. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44423. __decorate([
  44424. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44425. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44426. __decorate([
  44427. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44428. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44429. __decorate([
  44430. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44431. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44432. __decorate([
  44433. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44434. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44435. __decorate([
  44436. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44437. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44438. __decorate([
  44439. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44440. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44441. __decorate([
  44442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44443. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44444. __decorate([
  44445. BABYLON.serialize("maxSimultaneousLights")
  44446. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44447. __decorate([
  44448. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44449. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44450. __decorate([
  44451. BABYLON.serialize("invertNormalMapX")
  44452. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44453. __decorate([
  44454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44455. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44456. __decorate([
  44457. BABYLON.serialize("invertNormalMapY")
  44458. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44459. __decorate([
  44460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44461. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44462. __decorate([
  44463. BABYLON.serialize("twoSidedLighting")
  44464. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44465. __decorate([
  44466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44467. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44468. __decorate([
  44469. BABYLON.serialize()
  44470. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44471. return StandardMaterial;
  44472. }(BABYLON.PushMaterial));
  44473. BABYLON.StandardMaterial = StandardMaterial;
  44474. })(BABYLON || (BABYLON = {}));
  44475. //# sourceMappingURL=babylon.standardMaterial.js.map
  44476. var BABYLON;
  44477. (function (BABYLON) {
  44478. /**
  44479. * Manages the defines for the PBR Material.
  44480. * @hiddenChildren
  44481. */
  44482. var PBRMaterialDefines = /** @class */ (function (_super) {
  44483. __extends(PBRMaterialDefines, _super);
  44484. /**
  44485. * Initializes the PBR Material defines.
  44486. */
  44487. function PBRMaterialDefines() {
  44488. var _this = _super.call(this) || this;
  44489. _this.PBR = true;
  44490. _this.MAINUV1 = false;
  44491. _this.MAINUV2 = false;
  44492. _this.UV1 = false;
  44493. _this.UV2 = false;
  44494. _this.ALBEDO = false;
  44495. _this.ALBEDODIRECTUV = 0;
  44496. _this.VERTEXCOLOR = false;
  44497. _this.AMBIENT = false;
  44498. _this.AMBIENTDIRECTUV = 0;
  44499. _this.AMBIENTINGRAYSCALE = false;
  44500. _this.OPACITY = false;
  44501. _this.VERTEXALPHA = false;
  44502. _this.OPACITYDIRECTUV = 0;
  44503. _this.OPACITYRGB = false;
  44504. _this.ALPHATEST = false;
  44505. _this.DEPTHPREPASS = false;
  44506. _this.ALPHABLEND = false;
  44507. _this.ALPHAFROMALBEDO = false;
  44508. _this.ALPHATESTVALUE = "0.5";
  44509. _this.SPECULAROVERALPHA = false;
  44510. _this.RADIANCEOVERALPHA = false;
  44511. _this.ALPHAFRESNEL = false;
  44512. _this.LINEARALPHAFRESNEL = false;
  44513. _this.PREMULTIPLYALPHA = false;
  44514. _this.EMISSIVE = false;
  44515. _this.EMISSIVEDIRECTUV = 0;
  44516. _this.REFLECTIVITY = false;
  44517. _this.REFLECTIVITYDIRECTUV = 0;
  44518. _this.SPECULARTERM = false;
  44519. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44520. _this.MICROSURFACEAUTOMATIC = false;
  44521. _this.LODBASEDMICROSFURACE = false;
  44522. _this.MICROSURFACEMAP = false;
  44523. _this.MICROSURFACEMAPDIRECTUV = 0;
  44524. _this.METALLICWORKFLOW = false;
  44525. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44526. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44527. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44528. _this.AOSTOREINMETALMAPRED = false;
  44529. _this.ENVIRONMENTBRDF = false;
  44530. _this.NORMAL = false;
  44531. _this.TANGENT = false;
  44532. _this.BUMP = false;
  44533. _this.BUMPDIRECTUV = 0;
  44534. _this.OBJECTSPACE_NORMALMAP = false;
  44535. _this.PARALLAX = false;
  44536. _this.PARALLAXOCCLUSION = false;
  44537. _this.NORMALXYSCALE = true;
  44538. _this.LIGHTMAP = false;
  44539. _this.LIGHTMAPDIRECTUV = 0;
  44540. _this.USELIGHTMAPASSHADOWMAP = false;
  44541. _this.GAMMALIGHTMAP = false;
  44542. _this.REFLECTION = false;
  44543. _this.REFLECTIONMAP_3D = false;
  44544. _this.REFLECTIONMAP_SPHERICAL = false;
  44545. _this.REFLECTIONMAP_PLANAR = false;
  44546. _this.REFLECTIONMAP_CUBIC = false;
  44547. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44548. _this.REFLECTIONMAP_PROJECTION = false;
  44549. _this.REFLECTIONMAP_SKYBOX = false;
  44550. _this.REFLECTIONMAP_EXPLICIT = false;
  44551. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44552. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44553. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44554. _this.INVERTCUBICMAP = false;
  44555. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44556. _this.USESPHERICALINVERTEX = false;
  44557. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44558. _this.LODINREFLECTIONALPHA = false;
  44559. _this.GAMMAREFLECTION = false;
  44560. _this.RADIANCEOCCLUSION = false;
  44561. _this.HORIZONOCCLUSION = false;
  44562. _this.REFRACTION = false;
  44563. _this.REFRACTIONMAP_3D = false;
  44564. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44565. _this.LODINREFRACTIONALPHA = false;
  44566. _this.GAMMAREFRACTION = false;
  44567. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44568. _this.INSTANCES = false;
  44569. _this.NUM_BONE_INFLUENCERS = 0;
  44570. _this.BonesPerMesh = 0;
  44571. _this.NONUNIFORMSCALING = false;
  44572. _this.MORPHTARGETS = false;
  44573. _this.MORPHTARGETS_NORMAL = false;
  44574. _this.MORPHTARGETS_TANGENT = false;
  44575. _this.NUM_MORPH_INFLUENCERS = 0;
  44576. _this.IMAGEPROCESSING = false;
  44577. _this.VIGNETTE = false;
  44578. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44579. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44580. _this.TONEMAPPING = false;
  44581. _this.CONTRAST = false;
  44582. _this.COLORCURVES = false;
  44583. _this.COLORGRADING = false;
  44584. _this.COLORGRADING3D = false;
  44585. _this.SAMPLER3DGREENDEPTH = false;
  44586. _this.SAMPLER3DBGRMAP = false;
  44587. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44588. _this.EXPOSURE = false;
  44589. _this.USEPHYSICALLIGHTFALLOFF = false;
  44590. _this.TWOSIDEDLIGHTING = false;
  44591. _this.SHADOWFLOAT = false;
  44592. _this.CLIPPLANE = false;
  44593. _this.POINTSIZE = false;
  44594. _this.FOG = false;
  44595. _this.LOGARITHMICDEPTH = false;
  44596. _this.FORCENORMALFORWARD = false;
  44597. _this.SPECULARAA = false;
  44598. _this.UNLIT = false;
  44599. _this.rebuild();
  44600. return _this;
  44601. }
  44602. /**
  44603. * Resets the PBR Material defines.
  44604. */
  44605. PBRMaterialDefines.prototype.reset = function () {
  44606. _super.prototype.reset.call(this);
  44607. this.ALPHATESTVALUE = "0.5";
  44608. this.PBR = true;
  44609. };
  44610. return PBRMaterialDefines;
  44611. }(BABYLON.MaterialDefines));
  44612. /**
  44613. * The Physically based material base class of BJS.
  44614. *
  44615. * This offers the main features of a standard PBR material.
  44616. * For more information, please refer to the documentation :
  44617. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44618. */
  44619. var PBRBaseMaterial = /** @class */ (function (_super) {
  44620. __extends(PBRBaseMaterial, _super);
  44621. /**
  44622. * Instantiates a new PBRMaterial instance.
  44623. *
  44624. * @param name The material name
  44625. * @param scene The scene the material will be use in.
  44626. */
  44627. function PBRBaseMaterial(name, scene) {
  44628. var _this = _super.call(this, name, scene) || this;
  44629. /**
  44630. * Intensity of the direct lights e.g. the four lights available in your scene.
  44631. * This impacts both the direct diffuse and specular highlights.
  44632. */
  44633. _this._directIntensity = 1.0;
  44634. /**
  44635. * Intensity of the emissive part of the material.
  44636. * This helps controlling the emissive effect without modifying the emissive color.
  44637. */
  44638. _this._emissiveIntensity = 1.0;
  44639. /**
  44640. * Intensity of the environment e.g. how much the environment will light the object
  44641. * either through harmonics for rough material or through the refelction for shiny ones.
  44642. */
  44643. _this._environmentIntensity = 1.0;
  44644. /**
  44645. * This is a special control allowing the reduction of the specular highlights coming from the
  44646. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44647. */
  44648. _this._specularIntensity = 1.0;
  44649. /**
  44650. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44651. */
  44652. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44653. /**
  44654. * Debug Control allowing disabling the bump map on this material.
  44655. */
  44656. _this._disableBumpMap = false;
  44657. /**
  44658. * AKA Occlusion Texture Intensity in other nomenclature.
  44659. */
  44660. _this._ambientTextureStrength = 1.0;
  44661. /**
  44662. * The color of a material in ambient lighting.
  44663. */
  44664. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44665. /**
  44666. * AKA Diffuse Color in other nomenclature.
  44667. */
  44668. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44669. /**
  44670. * AKA Specular Color in other nomenclature.
  44671. */
  44672. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44673. /**
  44674. * The color applied when light is reflected from a material.
  44675. */
  44676. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44677. /**
  44678. * The color applied when light is emitted from a material.
  44679. */
  44680. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44681. /**
  44682. * AKA Glossiness in other nomenclature.
  44683. */
  44684. _this._microSurface = 0.9;
  44685. /**
  44686. * source material index of refraction (IOR)' / 'destination material IOR.
  44687. */
  44688. _this._indexOfRefraction = 0.66;
  44689. /**
  44690. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44691. */
  44692. _this._invertRefractionY = false;
  44693. /**
  44694. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44695. * Materials half opaque for instance using refraction could benefit from this control.
  44696. */
  44697. _this._linkRefractionWithTransparency = false;
  44698. /**
  44699. * Specifies that the material will use the light map as a show map.
  44700. */
  44701. _this._useLightmapAsShadowmap = false;
  44702. /**
  44703. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44704. * makes the reflect vector face the model (under horizon).
  44705. */
  44706. _this._useHorizonOcclusion = true;
  44707. /**
  44708. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44709. * too much the area relying on ambient texture to define their ambient occlusion.
  44710. */
  44711. _this._useRadianceOcclusion = true;
  44712. /**
  44713. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44714. */
  44715. _this._useAlphaFromAlbedoTexture = false;
  44716. /**
  44717. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44718. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44719. */
  44720. _this._useSpecularOverAlpha = true;
  44721. /**
  44722. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44723. */
  44724. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44725. /**
  44726. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44727. */
  44728. _this._useRoughnessFromMetallicTextureAlpha = true;
  44729. /**
  44730. * Specifies if the metallic texture contains the roughness information in its green channel.
  44731. */
  44732. _this._useRoughnessFromMetallicTextureGreen = false;
  44733. /**
  44734. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44735. */
  44736. _this._useMetallnessFromMetallicTextureBlue = false;
  44737. /**
  44738. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44739. */
  44740. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44741. /**
  44742. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44743. */
  44744. _this._useAmbientInGrayScale = false;
  44745. /**
  44746. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44747. * The material will try to infer what glossiness each pixel should be.
  44748. */
  44749. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44750. /**
  44751. * BJS is using an harcoded light falloff based on a manually sets up range.
  44752. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44753. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44754. */
  44755. _this._usePhysicalLightFalloff = true;
  44756. /**
  44757. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44758. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44759. */
  44760. _this._useRadianceOverAlpha = true;
  44761. /**
  44762. * Allows using an object space normal map (instead of tangent space).
  44763. */
  44764. _this._useObjectSpaceNormalMap = false;
  44765. /**
  44766. * Allows using the bump map in parallax mode.
  44767. */
  44768. _this._useParallax = false;
  44769. /**
  44770. * Allows using the bump map in parallax occlusion mode.
  44771. */
  44772. _this._useParallaxOcclusion = false;
  44773. /**
  44774. * Controls the scale bias of the parallax mode.
  44775. */
  44776. _this._parallaxScaleBias = 0.05;
  44777. /**
  44778. * If sets to true, disables all the lights affecting the material.
  44779. */
  44780. _this._disableLighting = false;
  44781. /**
  44782. * Number of Simultaneous lights allowed on the material.
  44783. */
  44784. _this._maxSimultaneousLights = 4;
  44785. /**
  44786. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44787. */
  44788. _this._invertNormalMapX = false;
  44789. /**
  44790. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44791. */
  44792. _this._invertNormalMapY = false;
  44793. /**
  44794. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44795. */
  44796. _this._twoSidedLighting = false;
  44797. /**
  44798. * Defines the alpha limits in alpha test mode.
  44799. */
  44800. _this._alphaCutOff = 0.4;
  44801. /**
  44802. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44803. */
  44804. _this._forceAlphaTest = false;
  44805. /**
  44806. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44807. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44808. */
  44809. _this._useAlphaFresnel = false;
  44810. /**
  44811. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44812. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44813. */
  44814. _this._useLinearAlphaFresnel = false;
  44815. /**
  44816. * The transparency mode of the material.
  44817. */
  44818. _this._transparencyMode = null;
  44819. /**
  44820. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44821. * from cos thetav and roughness:
  44822. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44823. */
  44824. _this._environmentBRDFTexture = null;
  44825. /**
  44826. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44827. */
  44828. _this._forceIrradianceInFragment = false;
  44829. /**
  44830. * Force normal to face away from face.
  44831. */
  44832. _this._forceNormalForward = false;
  44833. /**
  44834. * Enables specular anti aliasing in the PBR shader.
  44835. * It will both interacts on the Geometry for analytical and IBL lighting.
  44836. * It also prefilter the roughness map based on the bump values.
  44837. */
  44838. _this._enableSpecularAntiAliasing = false;
  44839. /**
  44840. * Stores the available render targets.
  44841. */
  44842. _this._renderTargets = new BABYLON.SmartArray(16);
  44843. /**
  44844. * Sets the global ambient color for the material used in lighting calculations.
  44845. */
  44846. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44847. /**
  44848. * If set to true, no lighting calculations will be applied.
  44849. */
  44850. _this._unlit = false;
  44851. // Setup the default processing configuration to the scene.
  44852. _this._attachImageProcessingConfiguration(null);
  44853. _this.getRenderTargetTextures = function () {
  44854. _this._renderTargets.reset();
  44855. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44856. _this._renderTargets.push(_this._reflectionTexture);
  44857. }
  44858. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44859. _this._renderTargets.push(_this._refractionTexture);
  44860. }
  44861. return _this._renderTargets;
  44862. };
  44863. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44864. return _this;
  44865. }
  44866. /**
  44867. * Attaches a new image processing configuration to the PBR Material.
  44868. * @param configuration
  44869. */
  44870. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44871. var _this = this;
  44872. if (configuration === this._imageProcessingConfiguration) {
  44873. return;
  44874. }
  44875. // Detaches observer.
  44876. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44877. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44878. }
  44879. // Pick the scene configuration if needed.
  44880. if (!configuration) {
  44881. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44882. }
  44883. else {
  44884. this._imageProcessingConfiguration = configuration;
  44885. }
  44886. // Attaches observer.
  44887. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44888. _this._markAllSubMeshesAsImageProcessingDirty();
  44889. });
  44890. };
  44891. /**
  44892. * Gets the name of the material class.
  44893. */
  44894. PBRBaseMaterial.prototype.getClassName = function () {
  44895. return "PBRBaseMaterial";
  44896. };
  44897. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44898. /**
  44899. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44900. */
  44901. get: function () {
  44902. return this._useLogarithmicDepth;
  44903. },
  44904. /**
  44905. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44906. */
  44907. set: function (value) {
  44908. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44909. },
  44910. enumerable: true,
  44911. configurable: true
  44912. });
  44913. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44914. /**
  44915. * Gets the current transparency mode.
  44916. */
  44917. get: function () {
  44918. return this._transparencyMode;
  44919. },
  44920. /**
  44921. * Sets the transparency mode of the material.
  44922. */
  44923. set: function (value) {
  44924. if (this._transparencyMode === value) {
  44925. return;
  44926. }
  44927. this._transparencyMode = value;
  44928. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44929. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44930. },
  44931. enumerable: true,
  44932. configurable: true
  44933. });
  44934. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44935. /**
  44936. * Returns true if alpha blending should be disabled.
  44937. */
  44938. get: function () {
  44939. return (this._linkRefractionWithTransparency ||
  44940. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44941. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44942. },
  44943. enumerable: true,
  44944. configurable: true
  44945. });
  44946. /**
  44947. * Specifies whether or not this material should be rendered in alpha blend mode.
  44948. */
  44949. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44950. if (this._disableAlphaBlending) {
  44951. return false;
  44952. }
  44953. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44954. };
  44955. /**
  44956. * Specifies if the mesh will require alpha blending.
  44957. * @param mesh - BJS mesh.
  44958. */
  44959. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44960. if (this._disableAlphaBlending) {
  44961. return false;
  44962. }
  44963. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44964. };
  44965. /**
  44966. * Specifies whether or not this material should be rendered in alpha test mode.
  44967. */
  44968. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44969. if (this._forceAlphaTest) {
  44970. return true;
  44971. }
  44972. if (this._linkRefractionWithTransparency) {
  44973. return false;
  44974. }
  44975. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44976. };
  44977. /**
  44978. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44979. */
  44980. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44981. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44982. };
  44983. /**
  44984. * Gets the texture used for the alpha test.
  44985. */
  44986. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44987. return this._albedoTexture;
  44988. };
  44989. /**
  44990. * Specifies that the submesh is ready to be used.
  44991. * @param mesh - BJS mesh.
  44992. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44993. * @param useInstances - Specifies that instances should be used.
  44994. * @returns - boolean indicating that the submesh is ready or not.
  44995. */
  44996. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44997. if (subMesh.effect && this.isFrozen) {
  44998. if (this._wasPreviouslyReady) {
  44999. return true;
  45000. }
  45001. }
  45002. if (!subMesh._materialDefines) {
  45003. subMesh._materialDefines = new PBRMaterialDefines();
  45004. }
  45005. var defines = subMesh._materialDefines;
  45006. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45007. if (defines._renderId === this.getScene().getRenderId()) {
  45008. return true;
  45009. }
  45010. }
  45011. var scene = this.getScene();
  45012. var engine = scene.getEngine();
  45013. if (defines._areTexturesDirty) {
  45014. if (scene.texturesEnabled) {
  45015. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45016. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45017. return false;
  45018. }
  45019. }
  45020. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45021. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45022. return false;
  45023. }
  45024. }
  45025. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45026. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45027. return false;
  45028. }
  45029. }
  45030. var reflectionTexture = this._getReflectionTexture();
  45031. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45032. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45033. return false;
  45034. }
  45035. }
  45036. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45037. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45038. return false;
  45039. }
  45040. }
  45041. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45042. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45043. return false;
  45044. }
  45045. }
  45046. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45047. if (this._metallicTexture) {
  45048. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45049. return false;
  45050. }
  45051. }
  45052. else if (this._reflectivityTexture) {
  45053. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45054. return false;
  45055. }
  45056. }
  45057. if (this._microSurfaceTexture) {
  45058. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45059. return false;
  45060. }
  45061. }
  45062. }
  45063. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45064. // Bump texture cannot be not blocking.
  45065. if (!this._bumpTexture.isReady()) {
  45066. return false;
  45067. }
  45068. }
  45069. var refractionTexture = this._getRefractionTexture();
  45070. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45071. if (!refractionTexture.isReadyOrNotBlocking()) {
  45072. return false;
  45073. }
  45074. }
  45075. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45076. // This is blocking.
  45077. if (!this._environmentBRDFTexture.isReady()) {
  45078. return false;
  45079. }
  45080. }
  45081. }
  45082. }
  45083. if (defines._areImageProcessingDirty) {
  45084. if (!this._imageProcessingConfiguration.isReady()) {
  45085. return false;
  45086. }
  45087. }
  45088. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45089. mesh.createNormals(true);
  45090. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45091. }
  45092. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45093. if (effect) {
  45094. scene.resetCachedMaterial();
  45095. subMesh.setEffect(effect, defines);
  45096. this.buildUniformLayout();
  45097. }
  45098. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45099. return false;
  45100. }
  45101. defines._renderId = scene.getRenderId();
  45102. this._wasPreviouslyReady = true;
  45103. return true;
  45104. };
  45105. /**
  45106. * Specifies if the material uses metallic roughness workflow.
  45107. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45108. */
  45109. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45110. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45111. return true;
  45112. }
  45113. return false;
  45114. };
  45115. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45116. if (onCompiled === void 0) { onCompiled = null; }
  45117. if (onError === void 0) { onError = null; }
  45118. if (useInstances === void 0) { useInstances = null; }
  45119. if (useClipPlane === void 0) { useClipPlane = null; }
  45120. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45121. if (!defines.isDirty) {
  45122. return null;
  45123. }
  45124. defines.markAsProcessed();
  45125. var scene = this.getScene();
  45126. var engine = scene.getEngine();
  45127. // Fallbacks
  45128. var fallbacks = new BABYLON.EffectFallbacks();
  45129. var fallbackRank = 0;
  45130. if (defines.USESPHERICALINVERTEX) {
  45131. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45132. }
  45133. if (defines.FOG) {
  45134. fallbacks.addFallback(fallbackRank, "FOG");
  45135. }
  45136. if (defines.SPECULARAA) {
  45137. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45138. }
  45139. if (defines.POINTSIZE) {
  45140. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45141. }
  45142. if (defines.LOGARITHMICDEPTH) {
  45143. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45144. }
  45145. if (defines.PARALLAX) {
  45146. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45147. }
  45148. if (defines.PARALLAXOCCLUSION) {
  45149. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45150. }
  45151. if (defines.ENVIRONMENTBRDF) {
  45152. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45153. }
  45154. if (defines.TANGENT) {
  45155. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45156. }
  45157. if (defines.BUMP) {
  45158. fallbacks.addFallback(fallbackRank++, "BUMP");
  45159. }
  45160. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45161. if (defines.SPECULARTERM) {
  45162. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45163. }
  45164. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45165. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45166. }
  45167. if (defines.LIGHTMAP) {
  45168. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45169. }
  45170. if (defines.NORMAL) {
  45171. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45172. }
  45173. if (defines.AMBIENT) {
  45174. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45175. }
  45176. if (defines.EMISSIVE) {
  45177. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45178. }
  45179. if (defines.VERTEXCOLOR) {
  45180. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45181. }
  45182. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45183. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45184. }
  45185. if (defines.MORPHTARGETS) {
  45186. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45187. }
  45188. //Attributes
  45189. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45190. if (defines.NORMAL) {
  45191. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45192. }
  45193. if (defines.TANGENT) {
  45194. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45195. }
  45196. if (defines.UV1) {
  45197. attribs.push(BABYLON.VertexBuffer.UVKind);
  45198. }
  45199. if (defines.UV2) {
  45200. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45201. }
  45202. if (defines.VERTEXCOLOR) {
  45203. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45204. }
  45205. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45206. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45207. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45208. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45209. "vFogInfos", "vFogColor", "pointSize",
  45210. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45211. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45212. "mBones",
  45213. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45214. "vLightingIntensity",
  45215. "logarithmicDepthConstant",
  45216. "vSphericalX", "vSphericalY", "vSphericalZ",
  45217. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45218. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45219. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45220. "vTangentSpaceParams"
  45221. ];
  45222. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45223. "bumpSampler", "lightmapSampler", "opacitySampler",
  45224. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45225. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45226. "microSurfaceSampler", "environmentBrdfSampler"];
  45227. var uniformBuffers = ["Material", "Scene"];
  45228. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45229. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45230. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45231. uniformsNames: uniforms,
  45232. uniformBuffersNames: uniformBuffers,
  45233. samplers: samplers,
  45234. defines: defines,
  45235. maxSimultaneousLights: this._maxSimultaneousLights
  45236. });
  45237. var join = defines.toString();
  45238. return engine.createEffect("pbr", {
  45239. attributes: attribs,
  45240. uniformsNames: uniforms,
  45241. uniformBuffersNames: uniformBuffers,
  45242. samplers: samplers,
  45243. defines: join,
  45244. fallbacks: fallbacks,
  45245. onCompiled: onCompiled,
  45246. onError: onError,
  45247. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45248. }, engine);
  45249. };
  45250. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45251. if (useInstances === void 0) { useInstances = null; }
  45252. if (useClipPlane === void 0) { useClipPlane = null; }
  45253. var scene = this.getScene();
  45254. var engine = scene.getEngine();
  45255. // Lights
  45256. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45257. defines._needNormals = true;
  45258. // Textures
  45259. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45260. if (defines._areTexturesDirty) {
  45261. defines._needUVs = false;
  45262. if (scene.texturesEnabled) {
  45263. if (scene.getEngine().getCaps().textureLOD) {
  45264. defines.LODBASEDMICROSFURACE = true;
  45265. }
  45266. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45267. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45268. }
  45269. else {
  45270. defines.ALBEDO = false;
  45271. }
  45272. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45273. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45274. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45275. }
  45276. else {
  45277. defines.AMBIENT = false;
  45278. }
  45279. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45280. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45281. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45282. }
  45283. else {
  45284. defines.OPACITY = false;
  45285. }
  45286. var reflectionTexture = this._getReflectionTexture();
  45287. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45288. defines.REFLECTION = true;
  45289. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45290. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45291. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45292. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45293. defines.INVERTCUBICMAP = true;
  45294. }
  45295. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45296. switch (reflectionTexture.coordinatesMode) {
  45297. case BABYLON.Texture.EXPLICIT_MODE:
  45298. defines.REFLECTIONMAP_EXPLICIT = true;
  45299. break;
  45300. case BABYLON.Texture.PLANAR_MODE:
  45301. defines.REFLECTIONMAP_PLANAR = true;
  45302. break;
  45303. case BABYLON.Texture.PROJECTION_MODE:
  45304. defines.REFLECTIONMAP_PROJECTION = true;
  45305. break;
  45306. case BABYLON.Texture.SKYBOX_MODE:
  45307. defines.REFLECTIONMAP_SKYBOX = true;
  45308. break;
  45309. case BABYLON.Texture.SPHERICAL_MODE:
  45310. defines.REFLECTIONMAP_SPHERICAL = true;
  45311. break;
  45312. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45313. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45314. break;
  45315. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45316. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45317. break;
  45318. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45319. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45320. break;
  45321. case BABYLON.Texture.CUBIC_MODE:
  45322. case BABYLON.Texture.INVCUBIC_MODE:
  45323. default:
  45324. defines.REFLECTIONMAP_CUBIC = true;
  45325. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45326. break;
  45327. }
  45328. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45329. if (reflectionTexture.sphericalPolynomial) {
  45330. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45331. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45332. defines.USESPHERICALINVERTEX = false;
  45333. }
  45334. else {
  45335. defines.USESPHERICALINVERTEX = true;
  45336. }
  45337. }
  45338. }
  45339. }
  45340. else {
  45341. defines.REFLECTION = false;
  45342. defines.REFLECTIONMAP_3D = false;
  45343. defines.REFLECTIONMAP_SPHERICAL = false;
  45344. defines.REFLECTIONMAP_PLANAR = false;
  45345. defines.REFLECTIONMAP_CUBIC = false;
  45346. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45347. defines.REFLECTIONMAP_PROJECTION = false;
  45348. defines.REFLECTIONMAP_SKYBOX = false;
  45349. defines.REFLECTIONMAP_EXPLICIT = false;
  45350. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45351. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45352. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45353. defines.INVERTCUBICMAP = false;
  45354. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45355. defines.USESPHERICALINVERTEX = false;
  45356. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45357. defines.LODINREFLECTIONALPHA = false;
  45358. defines.GAMMAREFLECTION = false;
  45359. }
  45360. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45361. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45362. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45363. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45364. }
  45365. else {
  45366. defines.LIGHTMAP = false;
  45367. }
  45368. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45369. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45370. }
  45371. else {
  45372. defines.EMISSIVE = false;
  45373. }
  45374. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45375. if (this._metallicTexture) {
  45376. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45377. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45378. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45379. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45380. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45381. }
  45382. else if (this._reflectivityTexture) {
  45383. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45384. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45385. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45386. }
  45387. else {
  45388. defines.REFLECTIVITY = false;
  45389. }
  45390. if (this._microSurfaceTexture) {
  45391. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45392. }
  45393. else {
  45394. defines.MICROSURFACEMAP = false;
  45395. }
  45396. }
  45397. else {
  45398. defines.REFLECTIVITY = false;
  45399. defines.MICROSURFACEMAP = false;
  45400. }
  45401. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45402. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45403. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45404. defines.PARALLAX = true;
  45405. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45406. }
  45407. else {
  45408. defines.PARALLAX = false;
  45409. }
  45410. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45411. }
  45412. else {
  45413. defines.BUMP = false;
  45414. }
  45415. var refractionTexture = this._getRefractionTexture();
  45416. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45417. defines.REFRACTION = true;
  45418. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45419. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45420. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45421. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45422. if (this._linkRefractionWithTransparency) {
  45423. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45424. }
  45425. }
  45426. else {
  45427. defines.REFRACTION = false;
  45428. }
  45429. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45430. defines.ENVIRONMENTBRDF = true;
  45431. }
  45432. else {
  45433. defines.ENVIRONMENTBRDF = false;
  45434. }
  45435. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45436. defines.ALPHAFROMALBEDO = true;
  45437. }
  45438. else {
  45439. defines.ALPHAFROMALBEDO = false;
  45440. }
  45441. }
  45442. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45443. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45444. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45445. if (!this.backFaceCulling && this._twoSidedLighting) {
  45446. defines.TWOSIDEDLIGHTING = true;
  45447. }
  45448. else {
  45449. defines.TWOSIDEDLIGHTING = false;
  45450. }
  45451. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45452. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45453. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45454. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45455. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45456. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45457. }
  45458. if (defines._areImageProcessingDirty) {
  45459. this._imageProcessingConfiguration.prepareDefines(defines);
  45460. }
  45461. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45462. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45463. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45464. // Misc.
  45465. if (defines._areMiscDirty) {
  45466. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45467. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45468. }
  45469. // Values that need to be evaluated on every frame
  45470. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45471. // Attribs
  45472. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45473. };
  45474. /**
  45475. * Force shader compilation
  45476. */
  45477. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45478. var _this = this;
  45479. var localOptions = __assign({ clipPlane: false }, options);
  45480. var defines = new PBRMaterialDefines();
  45481. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45482. if (effect.isReady()) {
  45483. if (onCompiled) {
  45484. onCompiled(this);
  45485. }
  45486. }
  45487. else {
  45488. effect.onCompileObservable.add(function () {
  45489. if (onCompiled) {
  45490. onCompiled(_this);
  45491. }
  45492. });
  45493. }
  45494. };
  45495. /**
  45496. * Initializes the uniform buffer layout for the shader.
  45497. */
  45498. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45499. // Order is important !
  45500. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45501. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45502. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45503. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45504. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45505. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45506. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45507. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45508. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45509. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45510. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45511. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45512. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45513. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45514. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45515. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45516. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45517. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45518. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45519. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45520. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45521. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45522. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45523. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45524. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45525. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45526. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45527. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45528. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45529. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45530. this._uniformBuffer.addUniform("pointSize", 1);
  45531. this._uniformBuffer.create();
  45532. };
  45533. /**
  45534. * Unbinds the textures.
  45535. */
  45536. PBRBaseMaterial.prototype.unbind = function () {
  45537. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45538. this._uniformBuffer.setTexture("reflectionSampler", null);
  45539. }
  45540. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45541. this._uniformBuffer.setTexture("refractionSampler", null);
  45542. }
  45543. _super.prototype.unbind.call(this);
  45544. };
  45545. /**
  45546. * Binds the submesh data.
  45547. * @param world - The world matrix.
  45548. * @param mesh - The BJS mesh.
  45549. * @param subMesh - A submesh of the BJS mesh.
  45550. */
  45551. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45552. var scene = this.getScene();
  45553. var defines = subMesh._materialDefines;
  45554. if (!defines) {
  45555. return;
  45556. }
  45557. var effect = subMesh.effect;
  45558. if (!effect) {
  45559. return;
  45560. }
  45561. this._activeEffect = effect;
  45562. // Matrices
  45563. this.bindOnlyWorldMatrix(world);
  45564. // Normal Matrix
  45565. if (defines.OBJECTSPACE_NORMALMAP) {
  45566. world.toNormalMatrix(this._normalMatrix);
  45567. this.bindOnlyNormalMatrix(this._normalMatrix);
  45568. }
  45569. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45570. // Bones
  45571. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45572. var reflectionTexture = null;
  45573. if (mustRebind) {
  45574. this._uniformBuffer.bindToEffect(effect, "Material");
  45575. this.bindViewProjection(effect);
  45576. reflectionTexture = this._getReflectionTexture();
  45577. var refractionTexture = this._getRefractionTexture();
  45578. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45579. // Texture uniforms
  45580. if (scene.texturesEnabled) {
  45581. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45582. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45583. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45584. }
  45585. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45586. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45587. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45588. }
  45589. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45590. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45591. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45592. }
  45593. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45594. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45595. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45596. if (reflectionTexture.boundingBoxSize) {
  45597. var cubeTexture = reflectionTexture;
  45598. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45599. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45600. }
  45601. var polynomials = reflectionTexture.sphericalPolynomial;
  45602. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45603. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45604. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45605. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45606. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45607. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45608. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45609. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45610. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45611. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45612. }
  45613. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45614. }
  45615. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45616. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45617. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45618. }
  45619. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45620. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45621. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45622. }
  45623. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45624. if (this._metallicTexture) {
  45625. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45626. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45627. }
  45628. else if (this._reflectivityTexture) {
  45629. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45630. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45631. }
  45632. if (this._microSurfaceTexture) {
  45633. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45634. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45635. }
  45636. }
  45637. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45638. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45639. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45640. if (scene._mirroredCameraPosition) {
  45641. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45642. }
  45643. else {
  45644. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45645. }
  45646. }
  45647. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45648. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45649. var depth = 1.0;
  45650. if (!refractionTexture.isCube) {
  45651. if (refractionTexture.depth) {
  45652. depth = refractionTexture.depth;
  45653. }
  45654. }
  45655. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45656. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45657. }
  45658. }
  45659. // Point size
  45660. if (this.pointsCloud) {
  45661. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45662. }
  45663. // Colors
  45664. if (defines.METALLICWORKFLOW) {
  45665. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45666. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45667. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45668. }
  45669. else {
  45670. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45671. }
  45672. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45673. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45674. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45675. // Misc
  45676. this._lightingInfos.x = this._directIntensity;
  45677. this._lightingInfos.y = this._emissiveIntensity;
  45678. this._lightingInfos.z = this._environmentIntensity;
  45679. this._lightingInfos.w = this._specularIntensity;
  45680. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45681. }
  45682. // Textures
  45683. if (scene.texturesEnabled) {
  45684. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45685. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45686. }
  45687. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45688. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45689. }
  45690. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45691. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45692. }
  45693. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45694. if (defines.LODBASEDMICROSFURACE) {
  45695. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45696. }
  45697. else {
  45698. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45699. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45700. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45701. }
  45702. }
  45703. if (defines.ENVIRONMENTBRDF) {
  45704. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45705. }
  45706. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45707. if (defines.LODBASEDMICROSFURACE) {
  45708. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45709. }
  45710. else {
  45711. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45712. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45713. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45714. }
  45715. }
  45716. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45717. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45718. }
  45719. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45720. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45721. }
  45722. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45723. if (this._metallicTexture) {
  45724. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45725. }
  45726. else if (this._reflectivityTexture) {
  45727. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45728. }
  45729. if (this._microSurfaceTexture) {
  45730. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45731. }
  45732. }
  45733. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45734. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45735. }
  45736. }
  45737. // Clip plane
  45738. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45739. // Colors
  45740. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45741. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45742. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45743. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45744. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45745. }
  45746. if (mustRebind || !this.isFrozen) {
  45747. // Lights
  45748. if (scene.lightsEnabled && !this._disableLighting) {
  45749. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45750. }
  45751. // View
  45752. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45753. this.bindView(effect);
  45754. }
  45755. // Fog
  45756. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45757. // Morph targets
  45758. if (defines.NUM_MORPH_INFLUENCERS) {
  45759. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45760. }
  45761. // image processing
  45762. this._imageProcessingConfiguration.bind(this._activeEffect);
  45763. // Log. depth
  45764. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45765. }
  45766. this._uniformBuffer.update();
  45767. this._afterBind(mesh, this._activeEffect);
  45768. };
  45769. /**
  45770. * Returns the animatable textures.
  45771. * @returns - Array of animatable textures.
  45772. */
  45773. PBRBaseMaterial.prototype.getAnimatables = function () {
  45774. var results = [];
  45775. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45776. results.push(this._albedoTexture);
  45777. }
  45778. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45779. results.push(this._ambientTexture);
  45780. }
  45781. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45782. results.push(this._opacityTexture);
  45783. }
  45784. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45785. results.push(this._reflectionTexture);
  45786. }
  45787. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45788. results.push(this._emissiveTexture);
  45789. }
  45790. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45791. results.push(this._metallicTexture);
  45792. }
  45793. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45794. results.push(this._reflectivityTexture);
  45795. }
  45796. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45797. results.push(this._bumpTexture);
  45798. }
  45799. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45800. results.push(this._lightmapTexture);
  45801. }
  45802. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45803. results.push(this._refractionTexture);
  45804. }
  45805. return results;
  45806. };
  45807. /**
  45808. * Returns the texture used for reflections.
  45809. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45810. */
  45811. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45812. if (this._reflectionTexture) {
  45813. return this._reflectionTexture;
  45814. }
  45815. return this.getScene().environmentTexture;
  45816. };
  45817. /**
  45818. * Returns the texture used for refraction or null if none is used.
  45819. * @returns - Refection texture if present. If no refraction texture and refraction
  45820. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45821. */
  45822. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45823. if (this._refractionTexture) {
  45824. return this._refractionTexture;
  45825. }
  45826. if (this._linkRefractionWithTransparency) {
  45827. return this.getScene().environmentTexture;
  45828. }
  45829. return null;
  45830. };
  45831. /**
  45832. * Disposes the resources of the material.
  45833. * @param forceDisposeEffect - Forces the disposal of effects.
  45834. * @param forceDisposeTextures - Forces the disposal of all textures.
  45835. */
  45836. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45837. if (forceDisposeTextures) {
  45838. if (this._albedoTexture) {
  45839. this._albedoTexture.dispose();
  45840. }
  45841. if (this._ambientTexture) {
  45842. this._ambientTexture.dispose();
  45843. }
  45844. if (this._opacityTexture) {
  45845. this._opacityTexture.dispose();
  45846. }
  45847. if (this._reflectionTexture) {
  45848. this._reflectionTexture.dispose();
  45849. }
  45850. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45851. this._environmentBRDFTexture.dispose();
  45852. }
  45853. if (this._emissiveTexture) {
  45854. this._emissiveTexture.dispose();
  45855. }
  45856. if (this._metallicTexture) {
  45857. this._metallicTexture.dispose();
  45858. }
  45859. if (this._reflectivityTexture) {
  45860. this._reflectivityTexture.dispose();
  45861. }
  45862. if (this._bumpTexture) {
  45863. this._bumpTexture.dispose();
  45864. }
  45865. if (this._lightmapTexture) {
  45866. this._lightmapTexture.dispose();
  45867. }
  45868. if (this._refractionTexture) {
  45869. this._refractionTexture.dispose();
  45870. }
  45871. }
  45872. this._renderTargets.dispose();
  45873. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45874. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45875. }
  45876. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45877. };
  45878. /**
  45879. * Stores the reflectivity values based on metallic roughness workflow.
  45880. */
  45881. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45882. __decorate([
  45883. BABYLON.serializeAsImageProcessingConfiguration()
  45884. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45885. __decorate([
  45886. BABYLON.serialize()
  45887. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45888. __decorate([
  45889. BABYLON.serialize()
  45890. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45891. return PBRBaseMaterial;
  45892. }(BABYLON.PushMaterial));
  45893. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45894. })(BABYLON || (BABYLON = {}));
  45895. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45896. var BABYLON;
  45897. (function (BABYLON) {
  45898. /**
  45899. * The Physically based simple base material of BJS.
  45900. *
  45901. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45902. * It is used as the base class for both the specGloss and metalRough conventions.
  45903. */
  45904. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45905. __extends(PBRBaseSimpleMaterial, _super);
  45906. /**
  45907. * Instantiates a new PBRMaterial instance.
  45908. *
  45909. * @param name The material name
  45910. * @param scene The scene the material will be use in.
  45911. */
  45912. function PBRBaseSimpleMaterial(name, scene) {
  45913. var _this = _super.call(this, name, scene) || this;
  45914. /**
  45915. * Number of Simultaneous lights allowed on the material.
  45916. */
  45917. _this.maxSimultaneousLights = 4;
  45918. /**
  45919. * If sets to true, disables all the lights affecting the material.
  45920. */
  45921. _this.disableLighting = false;
  45922. /**
  45923. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45924. */
  45925. _this.invertNormalMapX = false;
  45926. /**
  45927. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45928. */
  45929. _this.invertNormalMapY = false;
  45930. /**
  45931. * Emissivie color used to self-illuminate the model.
  45932. */
  45933. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45934. /**
  45935. * Occlusion Channel Strenght.
  45936. */
  45937. _this.occlusionStrength = 1.0;
  45938. _this.useLightmapAsShadowmap = false;
  45939. _this._useAlphaFromAlbedoTexture = true;
  45940. _this._useAmbientInGrayScale = true;
  45941. return _this;
  45942. }
  45943. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45944. /**
  45945. * Gets the current double sided mode.
  45946. */
  45947. get: function () {
  45948. return this._twoSidedLighting;
  45949. },
  45950. /**
  45951. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45952. */
  45953. set: function (value) {
  45954. if (this._twoSidedLighting === value) {
  45955. return;
  45956. }
  45957. this._twoSidedLighting = value;
  45958. this.backFaceCulling = !value;
  45959. this._markAllSubMeshesAsTexturesDirty();
  45960. },
  45961. enumerable: true,
  45962. configurable: true
  45963. });
  45964. /**
  45965. * Return the active textures of the material.
  45966. */
  45967. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45968. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45969. if (this.environmentTexture) {
  45970. activeTextures.push(this.environmentTexture);
  45971. }
  45972. if (this.normalTexture) {
  45973. activeTextures.push(this.normalTexture);
  45974. }
  45975. if (this.emissiveTexture) {
  45976. activeTextures.push(this.emissiveTexture);
  45977. }
  45978. if (this.occlusionTexture) {
  45979. activeTextures.push(this.occlusionTexture);
  45980. }
  45981. if (this.lightmapTexture) {
  45982. activeTextures.push(this.lightmapTexture);
  45983. }
  45984. return activeTextures;
  45985. };
  45986. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45987. if (_super.prototype.hasTexture.call(this, texture)) {
  45988. return true;
  45989. }
  45990. if (this.lightmapTexture === texture) {
  45991. return true;
  45992. }
  45993. return false;
  45994. };
  45995. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45996. return "PBRBaseSimpleMaterial";
  45997. };
  45998. __decorate([
  45999. BABYLON.serialize(),
  46000. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46001. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46002. __decorate([
  46003. BABYLON.serialize(),
  46004. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46005. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46006. __decorate([
  46007. BABYLON.serializeAsTexture(),
  46008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46009. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46010. __decorate([
  46011. BABYLON.serialize(),
  46012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46013. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46014. __decorate([
  46015. BABYLON.serialize(),
  46016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46017. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46018. __decorate([
  46019. BABYLON.serializeAsTexture(),
  46020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46021. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46022. __decorate([
  46023. BABYLON.serializeAsColor3("emissive"),
  46024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46025. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46026. __decorate([
  46027. BABYLON.serializeAsTexture(),
  46028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46029. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46030. __decorate([
  46031. BABYLON.serialize(),
  46032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46033. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46034. __decorate([
  46035. BABYLON.serializeAsTexture(),
  46036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46037. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46038. __decorate([
  46039. BABYLON.serialize(),
  46040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46041. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46042. __decorate([
  46043. BABYLON.serialize()
  46044. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46045. __decorate([
  46046. BABYLON.serializeAsTexture(),
  46047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46048. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46049. __decorate([
  46050. BABYLON.serialize(),
  46051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46052. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46053. return PBRBaseSimpleMaterial;
  46054. }(BABYLON.PBRBaseMaterial));
  46055. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46056. })(BABYLON || (BABYLON = {}));
  46057. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46058. var BABYLON;
  46059. (function (BABYLON) {
  46060. /**
  46061. * The Physically based material of BJS.
  46062. *
  46063. * This offers the main features of a standard PBR material.
  46064. * For more information, please refer to the documentation :
  46065. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46066. */
  46067. var PBRMaterial = /** @class */ (function (_super) {
  46068. __extends(PBRMaterial, _super);
  46069. /**
  46070. * Instantiates a new PBRMaterial instance.
  46071. *
  46072. * @param name The material name
  46073. * @param scene The scene the material will be use in.
  46074. */
  46075. function PBRMaterial(name, scene) {
  46076. var _this = _super.call(this, name, scene) || this;
  46077. /**
  46078. * Intensity of the direct lights e.g. the four lights available in your scene.
  46079. * This impacts both the direct diffuse and specular highlights.
  46080. */
  46081. _this.directIntensity = 1.0;
  46082. /**
  46083. * Intensity of the emissive part of the material.
  46084. * This helps controlling the emissive effect without modifying the emissive color.
  46085. */
  46086. _this.emissiveIntensity = 1.0;
  46087. /**
  46088. * Intensity of the environment e.g. how much the environment will light the object
  46089. * either through harmonics for rough material or through the refelction for shiny ones.
  46090. */
  46091. _this.environmentIntensity = 1.0;
  46092. /**
  46093. * This is a special control allowing the reduction of the specular highlights coming from the
  46094. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46095. */
  46096. _this.specularIntensity = 1.0;
  46097. /**
  46098. * Debug Control allowing disabling the bump map on this material.
  46099. */
  46100. _this.disableBumpMap = false;
  46101. /**
  46102. * AKA Occlusion Texture Intensity in other nomenclature.
  46103. */
  46104. _this.ambientTextureStrength = 1.0;
  46105. /**
  46106. * The color of a material in ambient lighting.
  46107. */
  46108. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46109. /**
  46110. * AKA Diffuse Color in other nomenclature.
  46111. */
  46112. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46113. /**
  46114. * AKA Specular Color in other nomenclature.
  46115. */
  46116. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46117. /**
  46118. * The color reflected from the material.
  46119. */
  46120. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46121. /**
  46122. * The color emitted from the material.
  46123. */
  46124. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46125. /**
  46126. * AKA Glossiness in other nomenclature.
  46127. */
  46128. _this.microSurface = 1.0;
  46129. /**
  46130. * source material index of refraction (IOR)' / 'destination material IOR.
  46131. */
  46132. _this.indexOfRefraction = 0.66;
  46133. /**
  46134. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46135. */
  46136. _this.invertRefractionY = false;
  46137. /**
  46138. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46139. * Materials half opaque for instance using refraction could benefit from this control.
  46140. */
  46141. _this.linkRefractionWithTransparency = false;
  46142. _this.useLightmapAsShadowmap = false;
  46143. /**
  46144. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46145. */
  46146. _this.useAlphaFromAlbedoTexture = false;
  46147. /**
  46148. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46149. */
  46150. _this.forceAlphaTest = false;
  46151. /**
  46152. * Defines the alpha limits in alpha test mode.
  46153. */
  46154. _this.alphaCutOff = 0.4;
  46155. /**
  46156. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46157. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46158. */
  46159. _this.useSpecularOverAlpha = true;
  46160. /**
  46161. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46162. */
  46163. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46164. /**
  46165. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46166. */
  46167. _this.useRoughnessFromMetallicTextureAlpha = true;
  46168. /**
  46169. * Specifies if the metallic texture contains the roughness information in its green channel.
  46170. */
  46171. _this.useRoughnessFromMetallicTextureGreen = false;
  46172. /**
  46173. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46174. */
  46175. _this.useMetallnessFromMetallicTextureBlue = false;
  46176. /**
  46177. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46178. */
  46179. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46180. /**
  46181. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46182. */
  46183. _this.useAmbientInGrayScale = false;
  46184. /**
  46185. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46186. * The material will try to infer what glossiness each pixel should be.
  46187. */
  46188. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46189. /**
  46190. * BJS is using an harcoded light falloff based on a manually sets up range.
  46191. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46192. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46193. */
  46194. _this.usePhysicalLightFalloff = true;
  46195. /**
  46196. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46197. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46198. */
  46199. _this.useRadianceOverAlpha = true;
  46200. /**
  46201. * Allows using an object space normal map (instead of tangent space).
  46202. */
  46203. _this.useObjectSpaceNormalMap = false;
  46204. /**
  46205. * Allows using the bump map in parallax mode.
  46206. */
  46207. _this.useParallax = false;
  46208. /**
  46209. * Allows using the bump map in parallax occlusion mode.
  46210. */
  46211. _this.useParallaxOcclusion = false;
  46212. /**
  46213. * Controls the scale bias of the parallax mode.
  46214. */
  46215. _this.parallaxScaleBias = 0.05;
  46216. /**
  46217. * If sets to true, disables all the lights affecting the material.
  46218. */
  46219. _this.disableLighting = false;
  46220. /**
  46221. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46222. */
  46223. _this.forceIrradianceInFragment = false;
  46224. /**
  46225. * Number of Simultaneous lights allowed on the material.
  46226. */
  46227. _this.maxSimultaneousLights = 4;
  46228. /**
  46229. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46230. */
  46231. _this.invertNormalMapX = false;
  46232. /**
  46233. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46234. */
  46235. _this.invertNormalMapY = false;
  46236. /**
  46237. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46238. */
  46239. _this.twoSidedLighting = false;
  46240. /**
  46241. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46242. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46243. */
  46244. _this.useAlphaFresnel = false;
  46245. /**
  46246. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46247. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46248. */
  46249. _this.useLinearAlphaFresnel = false;
  46250. /**
  46251. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46252. * And/Or occlude the blended part.
  46253. */
  46254. _this.environmentBRDFTexture = null;
  46255. /**
  46256. * Force normal to face away from face.
  46257. */
  46258. _this.forceNormalForward = false;
  46259. /**
  46260. * Enables specular anti aliasing in the PBR shader.
  46261. * It will both interacts on the Geometry for analytical and IBL lighting.
  46262. * It also prefilter the roughness map based on the bump values.
  46263. */
  46264. _this.enableSpecularAntiAliasing = false;
  46265. /**
  46266. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46267. * makes the reflect vector face the model (under horizon).
  46268. */
  46269. _this.useHorizonOcclusion = true;
  46270. /**
  46271. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46272. * too much the area relying on ambient texture to define their ambient occlusion.
  46273. */
  46274. _this.useRadianceOcclusion = true;
  46275. /**
  46276. * If set to true, no lighting calculations will be applied.
  46277. */
  46278. _this.unlit = false;
  46279. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46280. return _this;
  46281. }
  46282. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46283. /**
  46284. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46285. */
  46286. get: function () {
  46287. return this._PBRMATERIAL_OPAQUE;
  46288. },
  46289. enumerable: true,
  46290. configurable: true
  46291. });
  46292. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46293. /**
  46294. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46295. */
  46296. get: function () {
  46297. return this._PBRMATERIAL_ALPHATEST;
  46298. },
  46299. enumerable: true,
  46300. configurable: true
  46301. });
  46302. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46303. /**
  46304. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46305. */
  46306. get: function () {
  46307. return this._PBRMATERIAL_ALPHABLEND;
  46308. },
  46309. enumerable: true,
  46310. configurable: true
  46311. });
  46312. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46313. /**
  46314. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46315. * They are also discarded below the alpha cutoff threshold to improve performances.
  46316. */
  46317. get: function () {
  46318. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46319. },
  46320. enumerable: true,
  46321. configurable: true
  46322. });
  46323. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46324. /**
  46325. * Gets the image processing configuration used either in this material.
  46326. */
  46327. get: function () {
  46328. return this._imageProcessingConfiguration;
  46329. },
  46330. /**
  46331. * Sets the Default image processing configuration used either in the this material.
  46332. *
  46333. * If sets to null, the scene one is in use.
  46334. */
  46335. set: function (value) {
  46336. this._attachImageProcessingConfiguration(value);
  46337. // Ensure the effect will be rebuilt.
  46338. this._markAllSubMeshesAsTexturesDirty();
  46339. },
  46340. enumerable: true,
  46341. configurable: true
  46342. });
  46343. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46344. /**
  46345. * Gets wether the color curves effect is enabled.
  46346. */
  46347. get: function () {
  46348. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46349. },
  46350. /**
  46351. * Sets wether the color curves effect is enabled.
  46352. */
  46353. set: function (value) {
  46354. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46355. },
  46356. enumerable: true,
  46357. configurable: true
  46358. });
  46359. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46360. /**
  46361. * Gets wether the color grading effect is enabled.
  46362. */
  46363. get: function () {
  46364. return this.imageProcessingConfiguration.colorGradingEnabled;
  46365. },
  46366. /**
  46367. * Gets wether the color grading effect is enabled.
  46368. */
  46369. set: function (value) {
  46370. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46371. },
  46372. enumerable: true,
  46373. configurable: true
  46374. });
  46375. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46376. /**
  46377. * Gets wether tonemapping is enabled or not.
  46378. */
  46379. get: function () {
  46380. return this._imageProcessingConfiguration.toneMappingEnabled;
  46381. },
  46382. /**
  46383. * Sets wether tonemapping is enabled or not
  46384. */
  46385. set: function (value) {
  46386. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46387. },
  46388. enumerable: true,
  46389. configurable: true
  46390. });
  46391. ;
  46392. ;
  46393. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46394. /**
  46395. * The camera exposure used on this material.
  46396. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46397. * This corresponds to a photographic exposure.
  46398. */
  46399. get: function () {
  46400. return this._imageProcessingConfiguration.exposure;
  46401. },
  46402. /**
  46403. * The camera exposure used on this material.
  46404. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46405. * This corresponds to a photographic exposure.
  46406. */
  46407. set: function (value) {
  46408. this._imageProcessingConfiguration.exposure = value;
  46409. },
  46410. enumerable: true,
  46411. configurable: true
  46412. });
  46413. ;
  46414. ;
  46415. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46416. /**
  46417. * Gets The camera contrast used on this material.
  46418. */
  46419. get: function () {
  46420. return this._imageProcessingConfiguration.contrast;
  46421. },
  46422. /**
  46423. * Sets The camera contrast used on this material.
  46424. */
  46425. set: function (value) {
  46426. this._imageProcessingConfiguration.contrast = value;
  46427. },
  46428. enumerable: true,
  46429. configurable: true
  46430. });
  46431. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46432. /**
  46433. * Gets the Color Grading 2D Lookup Texture.
  46434. */
  46435. get: function () {
  46436. return this._imageProcessingConfiguration.colorGradingTexture;
  46437. },
  46438. /**
  46439. * Sets the Color Grading 2D Lookup Texture.
  46440. */
  46441. set: function (value) {
  46442. this._imageProcessingConfiguration.colorGradingTexture = value;
  46443. },
  46444. enumerable: true,
  46445. configurable: true
  46446. });
  46447. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46448. /**
  46449. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46450. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46451. * 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;
  46452. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46453. */
  46454. get: function () {
  46455. return this._imageProcessingConfiguration.colorCurves;
  46456. },
  46457. /**
  46458. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46459. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46460. * 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;
  46461. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46462. */
  46463. set: function (value) {
  46464. this._imageProcessingConfiguration.colorCurves = value;
  46465. },
  46466. enumerable: true,
  46467. configurable: true
  46468. });
  46469. /**
  46470. * Returns the name of this material class.
  46471. */
  46472. PBRMaterial.prototype.getClassName = function () {
  46473. return "PBRMaterial";
  46474. };
  46475. /**
  46476. * Returns an array of the actively used textures.
  46477. * @returns - Array of BaseTextures
  46478. */
  46479. PBRMaterial.prototype.getActiveTextures = function () {
  46480. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46481. if (this._albedoTexture) {
  46482. activeTextures.push(this._albedoTexture);
  46483. }
  46484. if (this._ambientTexture) {
  46485. activeTextures.push(this._ambientTexture);
  46486. }
  46487. if (this._opacityTexture) {
  46488. activeTextures.push(this._opacityTexture);
  46489. }
  46490. if (this._reflectionTexture) {
  46491. activeTextures.push(this._reflectionTexture);
  46492. }
  46493. if (this._emissiveTexture) {
  46494. activeTextures.push(this._emissiveTexture);
  46495. }
  46496. if (this._reflectivityTexture) {
  46497. activeTextures.push(this._reflectivityTexture);
  46498. }
  46499. if (this._metallicTexture) {
  46500. activeTextures.push(this._metallicTexture);
  46501. }
  46502. if (this._microSurfaceTexture) {
  46503. activeTextures.push(this._microSurfaceTexture);
  46504. }
  46505. if (this._bumpTexture) {
  46506. activeTextures.push(this._bumpTexture);
  46507. }
  46508. if (this._lightmapTexture) {
  46509. activeTextures.push(this._lightmapTexture);
  46510. }
  46511. if (this._refractionTexture) {
  46512. activeTextures.push(this._refractionTexture);
  46513. }
  46514. return activeTextures;
  46515. };
  46516. /**
  46517. * Checks to see if a texture is used in the material.
  46518. * @param texture - Base texture to use.
  46519. * @returns - Boolean specifying if a texture is used in the material.
  46520. */
  46521. PBRMaterial.prototype.hasTexture = function (texture) {
  46522. if (_super.prototype.hasTexture.call(this, texture)) {
  46523. return true;
  46524. }
  46525. if (this._albedoTexture === texture) {
  46526. return true;
  46527. }
  46528. if (this._ambientTexture === texture) {
  46529. return true;
  46530. }
  46531. if (this._opacityTexture === texture) {
  46532. return true;
  46533. }
  46534. if (this._reflectionTexture === texture) {
  46535. return true;
  46536. }
  46537. if (this._reflectivityTexture === texture) {
  46538. return true;
  46539. }
  46540. if (this._metallicTexture === texture) {
  46541. return true;
  46542. }
  46543. if (this._microSurfaceTexture === texture) {
  46544. return true;
  46545. }
  46546. if (this._bumpTexture === texture) {
  46547. return true;
  46548. }
  46549. if (this._lightmapTexture === texture) {
  46550. return true;
  46551. }
  46552. if (this._refractionTexture === texture) {
  46553. return true;
  46554. }
  46555. return false;
  46556. };
  46557. /**
  46558. * Makes a duplicate of the current material.
  46559. * @param name - name to use for the new material.
  46560. */
  46561. PBRMaterial.prototype.clone = function (name) {
  46562. var _this = this;
  46563. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46564. clone.id = name;
  46565. clone.name = name;
  46566. return clone;
  46567. };
  46568. /**
  46569. * Serializes this PBR Material.
  46570. * @returns - An object with the serialized material.
  46571. */
  46572. PBRMaterial.prototype.serialize = function () {
  46573. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46574. serializationObject.customType = "BABYLON.PBRMaterial";
  46575. return serializationObject;
  46576. };
  46577. // Statics
  46578. /**
  46579. * Parses a PBR Material from a serialized object.
  46580. * @param source - Serialized object.
  46581. * @param scene - BJS scene instance.
  46582. * @param rootUrl - url for the scene object
  46583. * @returns - PBRMaterial
  46584. */
  46585. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46586. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46587. };
  46588. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46589. /**
  46590. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46591. */
  46592. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46593. /**
  46594. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46595. */
  46596. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46597. /**
  46598. * 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.
  46599. * They are also discarded below the alpha cutoff threshold to improve performances.
  46600. */
  46601. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46602. __decorate([
  46603. BABYLON.serialize(),
  46604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46605. ], PBRMaterial.prototype, "directIntensity", void 0);
  46606. __decorate([
  46607. BABYLON.serialize(),
  46608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46609. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46610. __decorate([
  46611. BABYLON.serialize(),
  46612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46613. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46614. __decorate([
  46615. BABYLON.serialize(),
  46616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46617. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46618. __decorate([
  46619. BABYLON.serialize(),
  46620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46621. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46622. __decorate([
  46623. BABYLON.serializeAsTexture(),
  46624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46625. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46626. __decorate([
  46627. BABYLON.serializeAsTexture(),
  46628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46629. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46630. __decorate([
  46631. BABYLON.serialize(),
  46632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46633. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46634. __decorate([
  46635. BABYLON.serializeAsTexture(),
  46636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46637. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46638. __decorate([
  46639. BABYLON.serializeAsTexture(),
  46640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46641. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46642. __decorate([
  46643. BABYLON.serializeAsTexture(),
  46644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46645. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46646. __decorate([
  46647. BABYLON.serializeAsTexture(),
  46648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46649. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46650. __decorate([
  46651. BABYLON.serializeAsTexture(),
  46652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46653. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46654. __decorate([
  46655. BABYLON.serialize(),
  46656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46657. ], PBRMaterial.prototype, "metallic", void 0);
  46658. __decorate([
  46659. BABYLON.serialize(),
  46660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46661. ], PBRMaterial.prototype, "roughness", void 0);
  46662. __decorate([
  46663. BABYLON.serializeAsTexture(),
  46664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46665. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46666. __decorate([
  46667. BABYLON.serializeAsTexture(),
  46668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46669. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46670. __decorate([
  46671. BABYLON.serializeAsTexture(),
  46672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46673. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46674. __decorate([
  46675. BABYLON.serializeAsTexture(),
  46676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46677. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46678. __decorate([
  46679. BABYLON.serializeAsColor3("ambient"),
  46680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46681. ], PBRMaterial.prototype, "ambientColor", void 0);
  46682. __decorate([
  46683. BABYLON.serializeAsColor3("albedo"),
  46684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46685. ], PBRMaterial.prototype, "albedoColor", void 0);
  46686. __decorate([
  46687. BABYLON.serializeAsColor3("reflectivity"),
  46688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46689. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46690. __decorate([
  46691. BABYLON.serializeAsColor3("reflection"),
  46692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46693. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46694. __decorate([
  46695. BABYLON.serializeAsColor3("emissive"),
  46696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46697. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46698. __decorate([
  46699. BABYLON.serialize(),
  46700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46701. ], PBRMaterial.prototype, "microSurface", void 0);
  46702. __decorate([
  46703. BABYLON.serialize(),
  46704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46705. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46706. __decorate([
  46707. BABYLON.serialize(),
  46708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46709. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46710. __decorate([
  46711. BABYLON.serialize(),
  46712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46713. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46714. __decorate([
  46715. BABYLON.serialize(),
  46716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46717. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46718. __decorate([
  46719. BABYLON.serialize(),
  46720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46721. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46722. __decorate([
  46723. BABYLON.serialize(),
  46724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46725. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46726. __decorate([
  46727. BABYLON.serialize(),
  46728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46729. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46730. __decorate([
  46731. BABYLON.serialize(),
  46732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46733. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46734. __decorate([
  46735. BABYLON.serialize(),
  46736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46737. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46738. __decorate([
  46739. BABYLON.serialize(),
  46740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46741. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46742. __decorate([
  46743. BABYLON.serialize(),
  46744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46745. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46746. __decorate([
  46747. BABYLON.serialize(),
  46748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46749. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46750. __decorate([
  46751. BABYLON.serialize(),
  46752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46753. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46754. __decorate([
  46755. BABYLON.serialize(),
  46756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46757. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46758. __decorate([
  46759. BABYLON.serialize(),
  46760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46761. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46762. __decorate([
  46763. BABYLON.serialize(),
  46764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46765. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46766. __decorate([
  46767. BABYLON.serialize(),
  46768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46769. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46770. __decorate([
  46771. BABYLON.serialize(),
  46772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46773. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46774. __decorate([
  46775. BABYLON.serialize(),
  46776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46777. ], PBRMaterial.prototype, "useParallax", void 0);
  46778. __decorate([
  46779. BABYLON.serialize(),
  46780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46781. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46782. __decorate([
  46783. BABYLON.serialize(),
  46784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46785. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46786. __decorate([
  46787. BABYLON.serialize(),
  46788. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46789. ], PBRMaterial.prototype, "disableLighting", void 0);
  46790. __decorate([
  46791. BABYLON.serialize(),
  46792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46793. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46794. __decorate([
  46795. BABYLON.serialize(),
  46796. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46797. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46798. __decorate([
  46799. BABYLON.serialize(),
  46800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46801. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46802. __decorate([
  46803. BABYLON.serialize(),
  46804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46805. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46806. __decorate([
  46807. BABYLON.serialize(),
  46808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46809. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46810. __decorate([
  46811. BABYLON.serialize(),
  46812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46813. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46814. __decorate([
  46815. BABYLON.serialize(),
  46816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46817. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46818. __decorate([
  46819. BABYLON.serializeAsTexture(),
  46820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46821. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46822. __decorate([
  46823. BABYLON.serialize(),
  46824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46825. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46826. __decorate([
  46827. BABYLON.serialize(),
  46828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46829. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46830. __decorate([
  46831. BABYLON.serialize(),
  46832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46833. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46834. __decorate([
  46835. BABYLON.serialize(),
  46836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46837. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46838. __decorate([
  46839. BABYLON.serialize(),
  46840. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46841. ], PBRMaterial.prototype, "unlit", void 0);
  46842. return PBRMaterial;
  46843. }(BABYLON.PBRBaseMaterial));
  46844. BABYLON.PBRMaterial = PBRMaterial;
  46845. })(BABYLON || (BABYLON = {}));
  46846. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46847. var BABYLON;
  46848. (function (BABYLON) {
  46849. /**
  46850. * The PBR material of BJS following the metal roughness convention.
  46851. *
  46852. * This fits to the PBR convention in the GLTF definition:
  46853. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46854. */
  46855. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46856. __extends(PBRMetallicRoughnessMaterial, _super);
  46857. /**
  46858. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46859. *
  46860. * @param name The material name
  46861. * @param scene The scene the material will be use in.
  46862. */
  46863. function PBRMetallicRoughnessMaterial(name, scene) {
  46864. var _this = _super.call(this, name, scene) || this;
  46865. _this._useRoughnessFromMetallicTextureAlpha = false;
  46866. _this._useRoughnessFromMetallicTextureGreen = true;
  46867. _this._useMetallnessFromMetallicTextureBlue = true;
  46868. _this.metallic = 1.0;
  46869. _this.roughness = 1.0;
  46870. return _this;
  46871. }
  46872. /**
  46873. * Return the currrent class name of the material.
  46874. */
  46875. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46876. return "PBRMetallicRoughnessMaterial";
  46877. };
  46878. /**
  46879. * Return the active textures of the material.
  46880. */
  46881. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46882. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46883. if (this.baseTexture) {
  46884. activeTextures.push(this.baseTexture);
  46885. }
  46886. if (this.metallicRoughnessTexture) {
  46887. activeTextures.push(this.metallicRoughnessTexture);
  46888. }
  46889. return activeTextures;
  46890. };
  46891. /**
  46892. * Checks to see if a texture is used in the material.
  46893. * @param texture - Base texture to use.
  46894. * @returns - Boolean specifying if a texture is used in the material.
  46895. */
  46896. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46897. if (_super.prototype.hasTexture.call(this, texture)) {
  46898. return true;
  46899. }
  46900. if (this.baseTexture === texture) {
  46901. return true;
  46902. }
  46903. if (this.metallicRoughnessTexture === texture) {
  46904. return true;
  46905. }
  46906. return false;
  46907. };
  46908. /**
  46909. * Makes a duplicate of the current material.
  46910. * @param name - name to use for the new material.
  46911. */
  46912. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46913. var _this = this;
  46914. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46915. clone.id = name;
  46916. clone.name = name;
  46917. return clone;
  46918. };
  46919. /**
  46920. * Serialize the material to a parsable JSON object.
  46921. */
  46922. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46923. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46924. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46925. return serializationObject;
  46926. };
  46927. /**
  46928. * Parses a JSON object correponding to the serialize function.
  46929. */
  46930. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46931. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46932. };
  46933. __decorate([
  46934. BABYLON.serializeAsColor3(),
  46935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46936. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46937. __decorate([
  46938. BABYLON.serializeAsTexture(),
  46939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46940. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46941. __decorate([
  46942. BABYLON.serialize(),
  46943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46944. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46945. __decorate([
  46946. BABYLON.serialize(),
  46947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46948. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46949. __decorate([
  46950. BABYLON.serializeAsTexture(),
  46951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46952. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46953. return PBRMetallicRoughnessMaterial;
  46954. }(BABYLON.PBRBaseSimpleMaterial));
  46955. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46956. })(BABYLON || (BABYLON = {}));
  46957. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46958. var BABYLON;
  46959. (function (BABYLON) {
  46960. /**
  46961. * The PBR material of BJS following the specular glossiness convention.
  46962. *
  46963. * This fits to the PBR convention in the GLTF definition:
  46964. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46965. */
  46966. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46967. __extends(PBRSpecularGlossinessMaterial, _super);
  46968. /**
  46969. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46970. *
  46971. * @param name The material name
  46972. * @param scene The scene the material will be use in.
  46973. */
  46974. function PBRSpecularGlossinessMaterial(name, scene) {
  46975. var _this = _super.call(this, name, scene) || this;
  46976. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46977. return _this;
  46978. }
  46979. /**
  46980. * Return the currrent class name of the material.
  46981. */
  46982. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46983. return "PBRSpecularGlossinessMaterial";
  46984. };
  46985. /**
  46986. * Return the active textures of the material.
  46987. */
  46988. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46989. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46990. if (this.diffuseTexture) {
  46991. activeTextures.push(this.diffuseTexture);
  46992. }
  46993. if (this.specularGlossinessTexture) {
  46994. activeTextures.push(this.specularGlossinessTexture);
  46995. }
  46996. return activeTextures;
  46997. };
  46998. /**
  46999. * Checks to see if a texture is used in the material.
  47000. * @param texture - Base texture to use.
  47001. * @returns - Boolean specifying if a texture is used in the material.
  47002. */
  47003. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47004. if (_super.prototype.hasTexture.call(this, texture)) {
  47005. return true;
  47006. }
  47007. if (this.diffuseTexture === texture) {
  47008. return true;
  47009. }
  47010. if (this.specularGlossinessTexture === texture) {
  47011. return true;
  47012. }
  47013. return false;
  47014. };
  47015. /**
  47016. * Makes a duplicate of the current material.
  47017. * @param name - name to use for the new material.
  47018. */
  47019. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47020. var _this = this;
  47021. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47022. clone.id = name;
  47023. clone.name = name;
  47024. return clone;
  47025. };
  47026. /**
  47027. * Serialize the material to a parsable JSON object.
  47028. */
  47029. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47030. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47031. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47032. return serializationObject;
  47033. };
  47034. /**
  47035. * Parses a JSON object correponding to the serialize function.
  47036. */
  47037. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47038. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47039. };
  47040. __decorate([
  47041. BABYLON.serializeAsColor3("diffuse"),
  47042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47043. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47044. __decorate([
  47045. BABYLON.serializeAsTexture(),
  47046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47047. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47048. __decorate([
  47049. BABYLON.serializeAsColor3("specular"),
  47050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47051. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47052. __decorate([
  47053. BABYLON.serialize(),
  47054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47055. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47056. __decorate([
  47057. BABYLON.serializeAsTexture(),
  47058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47059. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47060. return PBRSpecularGlossinessMaterial;
  47061. }(BABYLON.PBRBaseSimpleMaterial));
  47062. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47063. })(BABYLON || (BABYLON = {}));
  47064. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47065. var BABYLON;
  47066. (function (BABYLON) {
  47067. BABYLON.CameraInputTypes = {};
  47068. var CameraInputsManager = /** @class */ (function () {
  47069. function CameraInputsManager(camera) {
  47070. this.attached = {};
  47071. this.camera = camera;
  47072. this.checkInputs = function () { };
  47073. }
  47074. /**
  47075. * Add an input method to a camera.
  47076. * builtin inputs example: camera.inputs.addGamepad();
  47077. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47078. * @param input camera input method
  47079. */
  47080. CameraInputsManager.prototype.add = function (input) {
  47081. var type = input.getSimpleName();
  47082. if (this.attached[type]) {
  47083. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47084. return;
  47085. }
  47086. this.attached[type] = input;
  47087. input.camera = this.camera;
  47088. //for checkInputs, we are dynamically creating a function
  47089. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47090. if (input.checkInputs) {
  47091. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47092. }
  47093. if (this.attachedElement) {
  47094. input.attachControl(this.attachedElement);
  47095. }
  47096. };
  47097. /**
  47098. * Remove a specific input method from a camera
  47099. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47100. * @param inputToRemove camera input method
  47101. */
  47102. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47103. for (var cam in this.attached) {
  47104. var input = this.attached[cam];
  47105. if (input === inputToRemove) {
  47106. input.detachControl(this.attachedElement);
  47107. input.camera = null;
  47108. delete this.attached[cam];
  47109. this.rebuildInputCheck();
  47110. }
  47111. }
  47112. };
  47113. CameraInputsManager.prototype.removeByType = function (inputType) {
  47114. for (var cam in this.attached) {
  47115. var input = this.attached[cam];
  47116. if (input.getClassName() === inputType) {
  47117. input.detachControl(this.attachedElement);
  47118. input.camera = null;
  47119. delete this.attached[cam];
  47120. this.rebuildInputCheck();
  47121. }
  47122. }
  47123. };
  47124. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47125. var current = this.checkInputs;
  47126. return function () {
  47127. current();
  47128. fn();
  47129. };
  47130. };
  47131. CameraInputsManager.prototype.attachInput = function (input) {
  47132. if (this.attachedElement) {
  47133. input.attachControl(this.attachedElement, this.noPreventDefault);
  47134. }
  47135. };
  47136. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47137. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47138. if (this.attachedElement) {
  47139. return;
  47140. }
  47141. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47142. this.attachedElement = element;
  47143. this.noPreventDefault = noPreventDefault;
  47144. for (var cam in this.attached) {
  47145. this.attached[cam].attachControl(element, noPreventDefault);
  47146. }
  47147. };
  47148. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47149. if (disconnect === void 0) { disconnect = false; }
  47150. if (this.attachedElement !== element) {
  47151. return;
  47152. }
  47153. for (var cam in this.attached) {
  47154. this.attached[cam].detachControl(element);
  47155. if (disconnect) {
  47156. this.attached[cam].camera = null;
  47157. }
  47158. }
  47159. this.attachedElement = null;
  47160. };
  47161. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47162. this.checkInputs = function () { };
  47163. for (var cam in this.attached) {
  47164. var input = this.attached[cam];
  47165. if (input.checkInputs) {
  47166. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47167. }
  47168. }
  47169. };
  47170. /**
  47171. * Remove all attached input methods from a camera
  47172. */
  47173. CameraInputsManager.prototype.clear = function () {
  47174. if (this.attachedElement) {
  47175. this.detachElement(this.attachedElement, true);
  47176. }
  47177. this.attached = {};
  47178. this.attachedElement = null;
  47179. this.checkInputs = function () { };
  47180. };
  47181. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47182. var inputs = {};
  47183. for (var cam in this.attached) {
  47184. var input = this.attached[cam];
  47185. var res = BABYLON.SerializationHelper.Serialize(input);
  47186. inputs[input.getClassName()] = res;
  47187. }
  47188. serializedCamera.inputsmgr = inputs;
  47189. };
  47190. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47191. var parsedInputs = parsedCamera.inputsmgr;
  47192. if (parsedInputs) {
  47193. this.clear();
  47194. for (var n in parsedInputs) {
  47195. var construct = BABYLON.CameraInputTypes[n];
  47196. if (construct) {
  47197. var parsedinput = parsedInputs[n];
  47198. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47199. this.add(input);
  47200. }
  47201. }
  47202. }
  47203. else {
  47204. //2016-03-08 this part is for managing backward compatibility
  47205. for (var n in this.attached) {
  47206. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47207. if (construct) {
  47208. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47209. this.remove(this.attached[n]);
  47210. this.add(input);
  47211. }
  47212. }
  47213. }
  47214. };
  47215. return CameraInputsManager;
  47216. }());
  47217. BABYLON.CameraInputsManager = CameraInputsManager;
  47218. })(BABYLON || (BABYLON = {}));
  47219. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47220. var BABYLON;
  47221. (function (BABYLON) {
  47222. var TargetCamera = /** @class */ (function (_super) {
  47223. __extends(TargetCamera, _super);
  47224. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47225. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47226. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47227. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47228. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47229. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47230. _this.speed = 2.0;
  47231. _this.noRotationConstraint = false;
  47232. _this.lockedTarget = null;
  47233. _this._currentTarget = BABYLON.Vector3.Zero();
  47234. _this._viewMatrix = BABYLON.Matrix.Zero();
  47235. _this._camMatrix = BABYLON.Matrix.Zero();
  47236. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47237. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47238. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47239. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47240. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47241. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47242. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47243. return _this;
  47244. }
  47245. TargetCamera.prototype.getFrontPosition = function (distance) {
  47246. this.getWorldMatrix();
  47247. var direction = this.getTarget().subtract(this.position);
  47248. direction.normalize();
  47249. direction.scaleInPlace(distance);
  47250. return this.globalPosition.add(direction);
  47251. };
  47252. TargetCamera.prototype._getLockedTargetPosition = function () {
  47253. if (!this.lockedTarget) {
  47254. return null;
  47255. }
  47256. if (this.lockedTarget.absolutePosition) {
  47257. this.lockedTarget.computeWorldMatrix();
  47258. }
  47259. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47260. };
  47261. TargetCamera.prototype.storeState = function () {
  47262. this._storedPosition = this.position.clone();
  47263. this._storedRotation = this.rotation.clone();
  47264. if (this.rotationQuaternion) {
  47265. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47266. }
  47267. return _super.prototype.storeState.call(this);
  47268. };
  47269. /**
  47270. * Restored camera state. You must call storeState() first
  47271. */
  47272. TargetCamera.prototype._restoreStateValues = function () {
  47273. if (!_super.prototype._restoreStateValues.call(this)) {
  47274. return false;
  47275. }
  47276. this.position = this._storedPosition.clone();
  47277. this.rotation = this._storedRotation.clone();
  47278. if (this.rotationQuaternion) {
  47279. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47280. }
  47281. this.cameraDirection.copyFromFloats(0, 0, 0);
  47282. this.cameraRotation.copyFromFloats(0, 0);
  47283. return true;
  47284. };
  47285. // Cache
  47286. TargetCamera.prototype._initCache = function () {
  47287. _super.prototype._initCache.call(this);
  47288. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47289. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47290. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47291. };
  47292. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47293. if (!ignoreParentClass) {
  47294. _super.prototype._updateCache.call(this);
  47295. }
  47296. var lockedTargetPosition = this._getLockedTargetPosition();
  47297. if (!lockedTargetPosition) {
  47298. this._cache.lockedTarget = null;
  47299. }
  47300. else {
  47301. if (!this._cache.lockedTarget) {
  47302. this._cache.lockedTarget = lockedTargetPosition.clone();
  47303. }
  47304. else {
  47305. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47306. }
  47307. }
  47308. this._cache.rotation.copyFrom(this.rotation);
  47309. if (this.rotationQuaternion)
  47310. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47311. };
  47312. // Synchronized
  47313. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47314. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47315. return false;
  47316. }
  47317. var lockedTargetPosition = this._getLockedTargetPosition();
  47318. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47319. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47320. };
  47321. // Methods
  47322. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47323. var engine = this.getEngine();
  47324. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47325. };
  47326. // Target
  47327. TargetCamera.prototype.setTarget = function (target) {
  47328. this.upVector.normalize();
  47329. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47330. this._camMatrix.invert();
  47331. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47332. var vDir = target.subtract(this.position);
  47333. if (vDir.x >= 0.0) {
  47334. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47335. }
  47336. else {
  47337. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47338. }
  47339. this.rotation.z = 0;
  47340. if (isNaN(this.rotation.x)) {
  47341. this.rotation.x = 0;
  47342. }
  47343. if (isNaN(this.rotation.y)) {
  47344. this.rotation.y = 0;
  47345. }
  47346. if (isNaN(this.rotation.z)) {
  47347. this.rotation.z = 0;
  47348. }
  47349. if (this.rotationQuaternion) {
  47350. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47351. }
  47352. };
  47353. /**
  47354. * Return the current target position of the camera. This value is expressed in local space.
  47355. */
  47356. TargetCamera.prototype.getTarget = function () {
  47357. return this._currentTarget;
  47358. };
  47359. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47360. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47361. };
  47362. TargetCamera.prototype._updatePosition = function () {
  47363. if (this.parent) {
  47364. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47365. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47366. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47367. return;
  47368. }
  47369. this.position.addInPlace(this.cameraDirection);
  47370. };
  47371. TargetCamera.prototype._checkInputs = function () {
  47372. var needToMove = this._decideIfNeedsToMove();
  47373. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47374. // Move
  47375. if (needToMove) {
  47376. this._updatePosition();
  47377. }
  47378. // Rotate
  47379. if (needToRotate) {
  47380. this.rotation.x += this.cameraRotation.x;
  47381. this.rotation.y += this.cameraRotation.y;
  47382. //rotate, if quaternion is set and rotation was used
  47383. if (this.rotationQuaternion) {
  47384. var len = this.rotation.lengthSquared();
  47385. if (len) {
  47386. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47387. }
  47388. }
  47389. if (!this.noRotationConstraint) {
  47390. var limit = (Math.PI / 2) * 0.95;
  47391. if (this.rotation.x > limit)
  47392. this.rotation.x = limit;
  47393. if (this.rotation.x < -limit)
  47394. this.rotation.x = -limit;
  47395. }
  47396. }
  47397. // Inertia
  47398. if (needToMove) {
  47399. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47400. this.cameraDirection.x = 0;
  47401. }
  47402. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47403. this.cameraDirection.y = 0;
  47404. }
  47405. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47406. this.cameraDirection.z = 0;
  47407. }
  47408. this.cameraDirection.scaleInPlace(this.inertia);
  47409. }
  47410. if (needToRotate) {
  47411. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47412. this.cameraRotation.x = 0;
  47413. }
  47414. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47415. this.cameraRotation.y = 0;
  47416. }
  47417. this.cameraRotation.scaleInPlace(this.inertia);
  47418. }
  47419. _super.prototype._checkInputs.call(this);
  47420. };
  47421. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47422. if (this.rotationQuaternion) {
  47423. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47424. }
  47425. else {
  47426. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47427. }
  47428. //update the up vector!
  47429. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47430. };
  47431. TargetCamera.prototype._getViewMatrix = function () {
  47432. if (this.lockedTarget) {
  47433. this.setTarget(this._getLockedTargetPosition());
  47434. }
  47435. // Compute
  47436. this._updateCameraRotationMatrix();
  47437. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47438. // Computing target and final matrix
  47439. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47440. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47441. return this._viewMatrix;
  47442. };
  47443. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47444. if (this.parent) {
  47445. var parentWorldMatrix = this.parent.getWorldMatrix();
  47446. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47447. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47448. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47449. this._markSyncedWithParent();
  47450. }
  47451. else {
  47452. this._globalPosition.copyFrom(this.position);
  47453. this._globalCurrentTarget.copyFrom(target);
  47454. this._globalCurrentUpVector.copyFrom(up);
  47455. }
  47456. if (this.getScene().useRightHandedSystem) {
  47457. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47458. }
  47459. else {
  47460. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47461. }
  47462. };
  47463. /**
  47464. * @override
  47465. * Override Camera.createRigCamera
  47466. */
  47467. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47468. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47469. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47470. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47471. if (!this.rotationQuaternion) {
  47472. this.rotationQuaternion = new BABYLON.Quaternion();
  47473. }
  47474. rigCamera._cameraRigParams = {};
  47475. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47476. }
  47477. return rigCamera;
  47478. }
  47479. return null;
  47480. };
  47481. /**
  47482. * @override
  47483. * Override Camera._updateRigCameras
  47484. */
  47485. TargetCamera.prototype._updateRigCameras = function () {
  47486. var camLeft = this._rigCameras[0];
  47487. var camRight = this._rigCameras[1];
  47488. switch (this.cameraRigMode) {
  47489. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47490. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47491. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47492. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47493. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47494. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47495. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47496. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47497. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47498. camLeft.setTarget(this.getTarget());
  47499. camRight.setTarget(this.getTarget());
  47500. break;
  47501. case BABYLON.Camera.RIG_MODE_VR:
  47502. if (camLeft.rotationQuaternion) {
  47503. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47504. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47505. }
  47506. else {
  47507. camLeft.rotation.copyFrom(this.rotation);
  47508. camRight.rotation.copyFrom(this.rotation);
  47509. }
  47510. camLeft.position.copyFrom(this.position);
  47511. camRight.position.copyFrom(this.position);
  47512. break;
  47513. }
  47514. _super.prototype._updateRigCameras.call(this);
  47515. };
  47516. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47517. if (!this._rigCamTransformMatrix) {
  47518. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47519. }
  47520. var target = this.getTarget();
  47521. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47522. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47523. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47524. };
  47525. TargetCamera.prototype.getClassName = function () {
  47526. return "TargetCamera";
  47527. };
  47528. __decorate([
  47529. BABYLON.serializeAsVector3()
  47530. ], TargetCamera.prototype, "rotation", void 0);
  47531. __decorate([
  47532. BABYLON.serialize()
  47533. ], TargetCamera.prototype, "speed", void 0);
  47534. __decorate([
  47535. BABYLON.serializeAsMeshReference("lockedTargetId")
  47536. ], TargetCamera.prototype, "lockedTarget", void 0);
  47537. return TargetCamera;
  47538. }(BABYLON.Camera));
  47539. BABYLON.TargetCamera = TargetCamera;
  47540. })(BABYLON || (BABYLON = {}));
  47541. //# sourceMappingURL=babylon.targetCamera.js.map
  47542. var BABYLON;
  47543. (function (BABYLON) {
  47544. var FreeCameraMouseInput = /** @class */ (function () {
  47545. function FreeCameraMouseInput(touchEnabled) {
  47546. if (touchEnabled === void 0) { touchEnabled = true; }
  47547. this.touchEnabled = touchEnabled;
  47548. this.buttons = [0, 1, 2];
  47549. this.angularSensibility = 2000.0;
  47550. this.previousPosition = null;
  47551. }
  47552. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47553. var _this = this;
  47554. var engine = this.camera.getEngine();
  47555. if (!this._pointerInput) {
  47556. this._pointerInput = function (p, s) {
  47557. var evt = p.event;
  47558. if (engine.isInVRExclusivePointerMode) {
  47559. return;
  47560. }
  47561. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47562. return;
  47563. }
  47564. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47565. return;
  47566. }
  47567. var srcElement = (evt.srcElement || evt.target);
  47568. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47569. try {
  47570. srcElement.setPointerCapture(evt.pointerId);
  47571. }
  47572. catch (e) {
  47573. //Nothing to do with the error. Execution will continue.
  47574. }
  47575. _this.previousPosition = {
  47576. x: evt.clientX,
  47577. y: evt.clientY
  47578. };
  47579. if (!noPreventDefault) {
  47580. evt.preventDefault();
  47581. element.focus();
  47582. }
  47583. }
  47584. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47585. try {
  47586. srcElement.releasePointerCapture(evt.pointerId);
  47587. }
  47588. catch (e) {
  47589. //Nothing to do with the error.
  47590. }
  47591. _this.previousPosition = null;
  47592. if (!noPreventDefault) {
  47593. evt.preventDefault();
  47594. }
  47595. }
  47596. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47597. if (!_this.previousPosition || engine.isPointerLock) {
  47598. return;
  47599. }
  47600. var offsetX = evt.clientX - _this.previousPosition.x;
  47601. if (_this.camera.getScene().useRightHandedSystem)
  47602. offsetX *= -1;
  47603. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47604. offsetX *= -1;
  47605. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47606. var offsetY = evt.clientY - _this.previousPosition.y;
  47607. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47608. _this.previousPosition = {
  47609. x: evt.clientX,
  47610. y: evt.clientY
  47611. };
  47612. if (!noPreventDefault) {
  47613. evt.preventDefault();
  47614. }
  47615. }
  47616. };
  47617. }
  47618. this._onMouseMove = function (evt) {
  47619. if (!engine.isPointerLock) {
  47620. return;
  47621. }
  47622. if (engine.isInVRExclusivePointerMode) {
  47623. return;
  47624. }
  47625. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47626. if (_this.camera.getScene().useRightHandedSystem)
  47627. offsetX *= -1;
  47628. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47629. offsetX *= -1;
  47630. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47631. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47632. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47633. _this.previousPosition = null;
  47634. if (!noPreventDefault) {
  47635. evt.preventDefault();
  47636. }
  47637. };
  47638. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47639. element.addEventListener("mousemove", this._onMouseMove, false);
  47640. };
  47641. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47642. if (this._observer && element) {
  47643. this.camera.getScene().onPointerObservable.remove(this._observer);
  47644. if (this._onMouseMove) {
  47645. element.removeEventListener("mousemove", this._onMouseMove);
  47646. }
  47647. this._observer = null;
  47648. this._onMouseMove = null;
  47649. this.previousPosition = null;
  47650. }
  47651. };
  47652. FreeCameraMouseInput.prototype.getClassName = function () {
  47653. return "FreeCameraMouseInput";
  47654. };
  47655. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47656. return "mouse";
  47657. };
  47658. __decorate([
  47659. BABYLON.serialize()
  47660. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47661. __decorate([
  47662. BABYLON.serialize()
  47663. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47664. return FreeCameraMouseInput;
  47665. }());
  47666. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47667. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47668. })(BABYLON || (BABYLON = {}));
  47669. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47670. var BABYLON;
  47671. (function (BABYLON) {
  47672. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47673. function FreeCameraKeyboardMoveInput() {
  47674. this._keys = new Array();
  47675. this.keysUp = [38];
  47676. this.keysDown = [40];
  47677. this.keysLeft = [37];
  47678. this.keysRight = [39];
  47679. }
  47680. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47681. var _this = this;
  47682. if (this._onCanvasBlurObserver) {
  47683. return;
  47684. }
  47685. this._scene = this.camera.getScene();
  47686. this._engine = this._scene.getEngine();
  47687. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47688. _this._keys = [];
  47689. });
  47690. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47691. var evt = info.event;
  47692. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47693. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47694. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47695. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47696. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47697. var index = _this._keys.indexOf(evt.keyCode);
  47698. if (index === -1) {
  47699. _this._keys.push(evt.keyCode);
  47700. }
  47701. if (!noPreventDefault) {
  47702. evt.preventDefault();
  47703. }
  47704. }
  47705. }
  47706. else {
  47707. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47708. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47709. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47710. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47711. var index = _this._keys.indexOf(evt.keyCode);
  47712. if (index >= 0) {
  47713. _this._keys.splice(index, 1);
  47714. }
  47715. if (!noPreventDefault) {
  47716. evt.preventDefault();
  47717. }
  47718. }
  47719. }
  47720. });
  47721. };
  47722. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47723. if (this._scene) {
  47724. if (this._onKeyboardObserver) {
  47725. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47726. }
  47727. if (this._onCanvasBlurObserver) {
  47728. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47729. }
  47730. this._onKeyboardObserver = null;
  47731. this._onCanvasBlurObserver = null;
  47732. }
  47733. this._keys = [];
  47734. };
  47735. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47736. if (this._onKeyboardObserver) {
  47737. var camera = this.camera;
  47738. // Keyboard
  47739. for (var index = 0; index < this._keys.length; index++) {
  47740. var keyCode = this._keys[index];
  47741. var speed = camera._computeLocalCameraSpeed();
  47742. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47743. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47744. }
  47745. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47746. camera._localDirection.copyFromFloats(0, 0, speed);
  47747. }
  47748. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47749. camera._localDirection.copyFromFloats(speed, 0, 0);
  47750. }
  47751. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47752. camera._localDirection.copyFromFloats(0, 0, -speed);
  47753. }
  47754. if (camera.getScene().useRightHandedSystem) {
  47755. camera._localDirection.z *= -1;
  47756. }
  47757. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47758. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47759. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47760. }
  47761. }
  47762. };
  47763. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47764. return "FreeCameraKeyboardMoveInput";
  47765. };
  47766. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47767. this._keys = [];
  47768. };
  47769. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47770. return "keyboard";
  47771. };
  47772. __decorate([
  47773. BABYLON.serialize()
  47774. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47775. __decorate([
  47776. BABYLON.serialize()
  47777. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47778. __decorate([
  47779. BABYLON.serialize()
  47780. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47781. __decorate([
  47782. BABYLON.serialize()
  47783. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47784. return FreeCameraKeyboardMoveInput;
  47785. }());
  47786. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47787. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47788. })(BABYLON || (BABYLON = {}));
  47789. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47790. var BABYLON;
  47791. (function (BABYLON) {
  47792. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47793. __extends(FreeCameraInputsManager, _super);
  47794. function FreeCameraInputsManager(camera) {
  47795. return _super.call(this, camera) || this;
  47796. }
  47797. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47798. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47799. return this;
  47800. };
  47801. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47802. if (touchEnabled === void 0) { touchEnabled = true; }
  47803. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47804. return this;
  47805. };
  47806. FreeCameraInputsManager.prototype.addGamepad = function () {
  47807. this.add(new BABYLON.FreeCameraGamepadInput());
  47808. return this;
  47809. };
  47810. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47811. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47812. return this;
  47813. };
  47814. FreeCameraInputsManager.prototype.addTouch = function () {
  47815. this.add(new BABYLON.FreeCameraTouchInput());
  47816. return this;
  47817. };
  47818. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47819. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47820. return this;
  47821. };
  47822. return FreeCameraInputsManager;
  47823. }(BABYLON.CameraInputsManager));
  47824. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47825. })(BABYLON || (BABYLON = {}));
  47826. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47827. var BABYLON;
  47828. (function (BABYLON) {
  47829. var FreeCamera = /** @class */ (function (_super) {
  47830. __extends(FreeCamera, _super);
  47831. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47832. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47833. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47834. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47835. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47836. _this.checkCollisions = false;
  47837. _this.applyGravity = false;
  47838. _this._needMoveForGravity = false;
  47839. _this._oldPosition = BABYLON.Vector3.Zero();
  47840. _this._diffPosition = BABYLON.Vector3.Zero();
  47841. _this._newPosition = BABYLON.Vector3.Zero();
  47842. // Collisions
  47843. _this._collisionMask = -1;
  47844. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47845. if (collidedMesh === void 0) { collidedMesh = null; }
  47846. //TODO move this to the collision coordinator!
  47847. if (_this.getScene().workerCollisions)
  47848. newPosition.multiplyInPlace(_this._collider._radius);
  47849. var updatePosition = function (newPos) {
  47850. _this._newPosition.copyFrom(newPos);
  47851. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47852. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47853. _this.position.addInPlace(_this._diffPosition);
  47854. if (_this.onCollide && collidedMesh) {
  47855. _this.onCollide(collidedMesh);
  47856. }
  47857. }
  47858. };
  47859. updatePosition(newPosition);
  47860. };
  47861. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47862. _this.inputs.addKeyboard().addMouse();
  47863. return _this;
  47864. }
  47865. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47866. //-- begin properties for backward compatibility for inputs
  47867. /**
  47868. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47869. * Higher values reduce sensitivity.
  47870. */
  47871. get: function () {
  47872. var mouse = this.inputs.attached["mouse"];
  47873. if (mouse)
  47874. return mouse.angularSensibility;
  47875. return 0;
  47876. },
  47877. /**
  47878. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47879. * Higher values reduce sensitivity.
  47880. */
  47881. set: function (value) {
  47882. var mouse = this.inputs.attached["mouse"];
  47883. if (mouse)
  47884. mouse.angularSensibility = value;
  47885. },
  47886. enumerable: true,
  47887. configurable: true
  47888. });
  47889. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47890. get: function () {
  47891. var keyboard = this.inputs.attached["keyboard"];
  47892. if (keyboard)
  47893. return keyboard.keysUp;
  47894. return [];
  47895. },
  47896. set: function (value) {
  47897. var keyboard = this.inputs.attached["keyboard"];
  47898. if (keyboard)
  47899. keyboard.keysUp = value;
  47900. },
  47901. enumerable: true,
  47902. configurable: true
  47903. });
  47904. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47905. get: function () {
  47906. var keyboard = this.inputs.attached["keyboard"];
  47907. if (keyboard)
  47908. return keyboard.keysDown;
  47909. return [];
  47910. },
  47911. set: function (value) {
  47912. var keyboard = this.inputs.attached["keyboard"];
  47913. if (keyboard)
  47914. keyboard.keysDown = value;
  47915. },
  47916. enumerable: true,
  47917. configurable: true
  47918. });
  47919. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47920. get: function () {
  47921. var keyboard = this.inputs.attached["keyboard"];
  47922. if (keyboard)
  47923. return keyboard.keysLeft;
  47924. return [];
  47925. },
  47926. set: function (value) {
  47927. var keyboard = this.inputs.attached["keyboard"];
  47928. if (keyboard)
  47929. keyboard.keysLeft = value;
  47930. },
  47931. enumerable: true,
  47932. configurable: true
  47933. });
  47934. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47935. get: function () {
  47936. var keyboard = this.inputs.attached["keyboard"];
  47937. if (keyboard)
  47938. return keyboard.keysRight;
  47939. return [];
  47940. },
  47941. set: function (value) {
  47942. var keyboard = this.inputs.attached["keyboard"];
  47943. if (keyboard)
  47944. keyboard.keysRight = value;
  47945. },
  47946. enumerable: true,
  47947. configurable: true
  47948. });
  47949. // Controls
  47950. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47951. this.inputs.attachElement(element, noPreventDefault);
  47952. };
  47953. FreeCamera.prototype.detachControl = function (element) {
  47954. this.inputs.detachElement(element);
  47955. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47956. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47957. };
  47958. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47959. get: function () {
  47960. return this._collisionMask;
  47961. },
  47962. set: function (mask) {
  47963. this._collisionMask = !isNaN(mask) ? mask : -1;
  47964. },
  47965. enumerable: true,
  47966. configurable: true
  47967. });
  47968. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47969. var globalPosition;
  47970. if (this.parent) {
  47971. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47972. }
  47973. else {
  47974. globalPosition = this.position;
  47975. }
  47976. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47977. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47978. if (!this._collider) {
  47979. this._collider = new BABYLON.Collider();
  47980. }
  47981. this._collider._radius = this.ellipsoid;
  47982. this._collider.collisionMask = this._collisionMask;
  47983. //no need for clone, as long as gravity is not on.
  47984. var actualDisplacement = displacement;
  47985. //add gravity to the direction to prevent the dual-collision checking
  47986. if (this.applyGravity) {
  47987. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47988. actualDisplacement = displacement.add(this.getScene().gravity);
  47989. }
  47990. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47991. };
  47992. FreeCamera.prototype._checkInputs = function () {
  47993. if (!this._localDirection) {
  47994. this._localDirection = BABYLON.Vector3.Zero();
  47995. this._transformedDirection = BABYLON.Vector3.Zero();
  47996. }
  47997. this.inputs.checkInputs();
  47998. _super.prototype._checkInputs.call(this);
  47999. };
  48000. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48001. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48002. };
  48003. FreeCamera.prototype._updatePosition = function () {
  48004. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48005. this._collideWithWorld(this.cameraDirection);
  48006. }
  48007. else {
  48008. _super.prototype._updatePosition.call(this);
  48009. }
  48010. };
  48011. FreeCamera.prototype.dispose = function () {
  48012. this.inputs.clear();
  48013. _super.prototype.dispose.call(this);
  48014. };
  48015. FreeCamera.prototype.getClassName = function () {
  48016. return "FreeCamera";
  48017. };
  48018. __decorate([
  48019. BABYLON.serializeAsVector3()
  48020. ], FreeCamera.prototype, "ellipsoid", void 0);
  48021. __decorate([
  48022. BABYLON.serializeAsVector3()
  48023. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48024. __decorate([
  48025. BABYLON.serialize()
  48026. ], FreeCamera.prototype, "checkCollisions", void 0);
  48027. __decorate([
  48028. BABYLON.serialize()
  48029. ], FreeCamera.prototype, "applyGravity", void 0);
  48030. return FreeCamera;
  48031. }(BABYLON.TargetCamera));
  48032. BABYLON.FreeCamera = FreeCamera;
  48033. })(BABYLON || (BABYLON = {}));
  48034. //# sourceMappingURL=babylon.freeCamera.js.map
  48035. var BABYLON;
  48036. (function (BABYLON) {
  48037. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48038. function ArcRotateCameraKeyboardMoveInput() {
  48039. this._keys = new Array();
  48040. this.keysUp = [38];
  48041. this.keysDown = [40];
  48042. this.keysLeft = [37];
  48043. this.keysRight = [39];
  48044. this.keysReset = [220];
  48045. this.panningSensibility = 50.0;
  48046. this.zoomingSensibility = 25.0;
  48047. this.useAltToZoom = true;
  48048. }
  48049. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48050. var _this = this;
  48051. if (this._onCanvasBlurObserver) {
  48052. return;
  48053. }
  48054. this._scene = this.camera.getScene();
  48055. this._engine = this._scene.getEngine();
  48056. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48057. _this._keys = [];
  48058. });
  48059. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48060. var evt = info.event;
  48061. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48062. _this._ctrlPressed = evt.ctrlKey;
  48063. _this._altPressed = evt.altKey;
  48064. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48065. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48066. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48067. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48068. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48069. var index = _this._keys.indexOf(evt.keyCode);
  48070. if (index === -1) {
  48071. _this._keys.push(evt.keyCode);
  48072. }
  48073. if (evt.preventDefault) {
  48074. if (!noPreventDefault) {
  48075. evt.preventDefault();
  48076. }
  48077. }
  48078. }
  48079. }
  48080. else {
  48081. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48082. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48083. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48084. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48085. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48086. var index = _this._keys.indexOf(evt.keyCode);
  48087. if (index >= 0) {
  48088. _this._keys.splice(index, 1);
  48089. }
  48090. if (evt.preventDefault) {
  48091. if (!noPreventDefault) {
  48092. evt.preventDefault();
  48093. }
  48094. }
  48095. }
  48096. }
  48097. });
  48098. };
  48099. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48100. if (this._scene) {
  48101. if (this._onKeyboardObserver) {
  48102. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48103. }
  48104. if (this._onCanvasBlurObserver) {
  48105. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48106. }
  48107. this._onKeyboardObserver = null;
  48108. this._onCanvasBlurObserver = null;
  48109. }
  48110. this._keys = [];
  48111. };
  48112. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48113. if (this._onKeyboardObserver) {
  48114. var camera = this.camera;
  48115. for (var index = 0; index < this._keys.length; index++) {
  48116. var keyCode = this._keys[index];
  48117. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48118. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48119. camera.inertialPanningX -= 1 / this.panningSensibility;
  48120. }
  48121. else {
  48122. camera.inertialAlphaOffset -= 0.01;
  48123. }
  48124. }
  48125. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48126. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48127. camera.inertialPanningY += 1 / this.panningSensibility;
  48128. }
  48129. else if (this._altPressed && this.useAltToZoom) {
  48130. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48131. }
  48132. else {
  48133. camera.inertialBetaOffset -= 0.01;
  48134. }
  48135. }
  48136. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48137. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48138. camera.inertialPanningX += 1 / this.panningSensibility;
  48139. }
  48140. else {
  48141. camera.inertialAlphaOffset += 0.01;
  48142. }
  48143. }
  48144. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48145. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48146. camera.inertialPanningY -= 1 / this.panningSensibility;
  48147. }
  48148. else if (this._altPressed && this.useAltToZoom) {
  48149. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48150. }
  48151. else {
  48152. camera.inertialBetaOffset += 0.01;
  48153. }
  48154. }
  48155. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48156. camera.restoreState();
  48157. }
  48158. }
  48159. }
  48160. };
  48161. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48162. return "ArcRotateCameraKeyboardMoveInput";
  48163. };
  48164. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48165. return "keyboard";
  48166. };
  48167. __decorate([
  48168. BABYLON.serialize()
  48169. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48170. __decorate([
  48171. BABYLON.serialize()
  48172. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48173. __decorate([
  48174. BABYLON.serialize()
  48175. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48176. __decorate([
  48177. BABYLON.serialize()
  48178. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48179. __decorate([
  48180. BABYLON.serialize()
  48181. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48182. __decorate([
  48183. BABYLON.serialize()
  48184. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48185. __decorate([
  48186. BABYLON.serialize()
  48187. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48188. __decorate([
  48189. BABYLON.serialize()
  48190. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48191. return ArcRotateCameraKeyboardMoveInput;
  48192. }());
  48193. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48194. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48195. })(BABYLON || (BABYLON = {}));
  48196. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48197. var BABYLON;
  48198. (function (BABYLON) {
  48199. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48200. function ArcRotateCameraMouseWheelInput() {
  48201. this.wheelPrecision = 3.0;
  48202. /**
  48203. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48204. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48205. */
  48206. this.wheelDeltaPercentage = 0;
  48207. }
  48208. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48209. var _this = this;
  48210. this._wheel = function (p, s) {
  48211. //sanity check - this should be a PointerWheel event.
  48212. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48213. return;
  48214. var event = p.event;
  48215. var delta = 0;
  48216. if (event.wheelDelta) {
  48217. if (_this.wheelDeltaPercentage) {
  48218. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48219. if (event.wheelDelta > 0) {
  48220. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48221. }
  48222. else {
  48223. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48224. }
  48225. }
  48226. else {
  48227. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48228. }
  48229. }
  48230. else if (event.detail) {
  48231. delta = -event.detail / _this.wheelPrecision;
  48232. }
  48233. if (delta)
  48234. _this.camera.inertialRadiusOffset += delta;
  48235. if (event.preventDefault) {
  48236. if (!noPreventDefault) {
  48237. event.preventDefault();
  48238. }
  48239. }
  48240. };
  48241. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48242. };
  48243. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48244. if (this._observer && element) {
  48245. this.camera.getScene().onPointerObservable.remove(this._observer);
  48246. this._observer = null;
  48247. this._wheel = null;
  48248. }
  48249. };
  48250. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48251. return "ArcRotateCameraMouseWheelInput";
  48252. };
  48253. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48254. return "mousewheel";
  48255. };
  48256. __decorate([
  48257. BABYLON.serialize()
  48258. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48259. __decorate([
  48260. BABYLON.serialize()
  48261. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48262. return ArcRotateCameraMouseWheelInput;
  48263. }());
  48264. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48265. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48266. })(BABYLON || (BABYLON = {}));
  48267. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48268. var BABYLON;
  48269. (function (BABYLON) {
  48270. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48271. function ArcRotateCameraPointersInput() {
  48272. this.buttons = [0, 1, 2];
  48273. this.angularSensibilityX = 1000.0;
  48274. this.angularSensibilityY = 1000.0;
  48275. this.pinchPrecision = 12.0;
  48276. /**
  48277. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48278. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48279. */
  48280. this.pinchDeltaPercentage = 0;
  48281. this.panningSensibility = 1000.0;
  48282. this.multiTouchPanning = true;
  48283. this.multiTouchPanAndZoom = true;
  48284. this._isPanClick = false;
  48285. this.pinchInwards = true;
  48286. }
  48287. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48288. var _this = this;
  48289. var engine = this.camera.getEngine();
  48290. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48291. var pointA = null;
  48292. var pointB = null;
  48293. var previousPinchSquaredDistance = 0;
  48294. var initialDistance = 0;
  48295. var twoFingerActivityCount = 0;
  48296. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48297. this._pointerInput = function (p, s) {
  48298. var evt = p.event;
  48299. var isTouch = p.event.pointerType === "touch";
  48300. if (engine.isInVRExclusivePointerMode) {
  48301. return;
  48302. }
  48303. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48304. return;
  48305. }
  48306. var srcElement = (evt.srcElement || evt.target);
  48307. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48308. try {
  48309. srcElement.setPointerCapture(evt.pointerId);
  48310. }
  48311. catch (e) {
  48312. //Nothing to do with the error. Execution will continue.
  48313. }
  48314. // Manage panning with pan button click
  48315. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48316. // manage pointers
  48317. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48318. if (pointA === null) {
  48319. pointA = cacheSoloPointer;
  48320. }
  48321. else if (pointB === null) {
  48322. pointB = cacheSoloPointer;
  48323. }
  48324. if (!noPreventDefault) {
  48325. evt.preventDefault();
  48326. element.focus();
  48327. }
  48328. }
  48329. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48330. _this.camera.restoreState();
  48331. }
  48332. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48333. try {
  48334. srcElement.releasePointerCapture(evt.pointerId);
  48335. }
  48336. catch (e) {
  48337. //Nothing to do with the error.
  48338. }
  48339. cacheSoloPointer = null;
  48340. previousPinchSquaredDistance = 0;
  48341. previousMultiTouchPanPosition.isPaning = false;
  48342. previousMultiTouchPanPosition.isPinching = false;
  48343. twoFingerActivityCount = 0;
  48344. initialDistance = 0;
  48345. if (!isTouch) {
  48346. pointB = null; // Mouse and pen are mono pointer
  48347. }
  48348. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48349. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48350. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48351. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48352. if (engine._badOS) {
  48353. pointA = pointB = null;
  48354. }
  48355. else {
  48356. //only remove the impacted pointer in case of multitouch allowing on most
  48357. //platforms switching from rotate to zoom and pan seamlessly.
  48358. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48359. pointA = pointB;
  48360. pointB = null;
  48361. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48362. }
  48363. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48364. pointB = null;
  48365. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48366. }
  48367. else {
  48368. pointA = pointB = null;
  48369. }
  48370. }
  48371. if (!noPreventDefault) {
  48372. evt.preventDefault();
  48373. }
  48374. }
  48375. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48376. if (!noPreventDefault) {
  48377. evt.preventDefault();
  48378. }
  48379. // One button down
  48380. if (pointA && pointB === null && cacheSoloPointer) {
  48381. if (_this.panningSensibility !== 0 &&
  48382. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48383. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48384. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48385. }
  48386. else {
  48387. var offsetX = evt.clientX - cacheSoloPointer.x;
  48388. var offsetY = evt.clientY - cacheSoloPointer.y;
  48389. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48390. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48391. }
  48392. cacheSoloPointer.x = evt.clientX;
  48393. cacheSoloPointer.y = evt.clientY;
  48394. }
  48395. // Two buttons down: pinch/pan
  48396. else if (pointA && pointB) {
  48397. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48398. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48399. ed.x = evt.clientX;
  48400. ed.y = evt.clientY;
  48401. var direction = _this.pinchInwards ? 1 : -1;
  48402. var distX = pointA.x - pointB.x;
  48403. var distY = pointA.y - pointB.y;
  48404. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48405. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48406. if (previousPinchSquaredDistance === 0) {
  48407. initialDistance = pinchDistance;
  48408. previousPinchSquaredDistance = pinchSquaredDistance;
  48409. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48410. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48411. return;
  48412. }
  48413. if (_this.multiTouchPanAndZoom) {
  48414. if (_this.pinchDeltaPercentage) {
  48415. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48416. }
  48417. else {
  48418. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48419. (_this.pinchPrecision *
  48420. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48421. direction);
  48422. }
  48423. if (_this.panningSensibility !== 0) {
  48424. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48425. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48426. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48427. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48428. previousMultiTouchPanPosition.x = pointersCenterX;
  48429. previousMultiTouchPanPosition.y = pointersCenterY;
  48430. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48431. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48432. }
  48433. }
  48434. else {
  48435. twoFingerActivityCount++;
  48436. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48437. if (_this.pinchDeltaPercentage) {
  48438. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48439. }
  48440. else {
  48441. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48442. (_this.pinchPrecision *
  48443. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48444. direction);
  48445. }
  48446. previousMultiTouchPanPosition.isPaning = false;
  48447. previousMultiTouchPanPosition.isPinching = true;
  48448. }
  48449. else {
  48450. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48451. if (!previousMultiTouchPanPosition.isPaning) {
  48452. previousMultiTouchPanPosition.isPaning = true;
  48453. previousMultiTouchPanPosition.isPinching = false;
  48454. previousMultiTouchPanPosition.x = ed.x;
  48455. previousMultiTouchPanPosition.y = ed.y;
  48456. return;
  48457. }
  48458. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48459. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48460. }
  48461. }
  48462. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48463. previousMultiTouchPanPosition.x = ed.x;
  48464. previousMultiTouchPanPosition.y = ed.y;
  48465. }
  48466. }
  48467. previousPinchSquaredDistance = pinchSquaredDistance;
  48468. }
  48469. }
  48470. };
  48471. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48472. this._onContextMenu = function (evt) {
  48473. evt.preventDefault();
  48474. };
  48475. if (!this.camera._useCtrlForPanning) {
  48476. element.addEventListener("contextmenu", this._onContextMenu, false);
  48477. }
  48478. this._onLostFocus = function () {
  48479. //this._keys = [];
  48480. pointA = pointB = null;
  48481. previousPinchSquaredDistance = 0;
  48482. previousMultiTouchPanPosition.isPaning = false;
  48483. previousMultiTouchPanPosition.isPinching = false;
  48484. twoFingerActivityCount = 0;
  48485. cacheSoloPointer = null;
  48486. initialDistance = 0;
  48487. };
  48488. this._onMouseMove = function (evt) {
  48489. if (!engine.isPointerLock) {
  48490. return;
  48491. }
  48492. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48493. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48494. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48495. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48496. if (!noPreventDefault) {
  48497. evt.preventDefault();
  48498. }
  48499. };
  48500. this._onGestureStart = function (e) {
  48501. if (window.MSGesture === undefined) {
  48502. return;
  48503. }
  48504. if (!_this._MSGestureHandler) {
  48505. _this._MSGestureHandler = new MSGesture();
  48506. _this._MSGestureHandler.target = element;
  48507. }
  48508. _this._MSGestureHandler.addPointer(e.pointerId);
  48509. };
  48510. this._onGesture = function (e) {
  48511. _this.camera.radius *= e.scale;
  48512. if (e.preventDefault) {
  48513. if (!noPreventDefault) {
  48514. e.stopPropagation();
  48515. e.preventDefault();
  48516. }
  48517. }
  48518. };
  48519. element.addEventListener("mousemove", this._onMouseMove, false);
  48520. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48521. element.addEventListener("MSGestureChange", this._onGesture, false);
  48522. BABYLON.Tools.RegisterTopRootEvents([
  48523. { name: "blur", handler: this._onLostFocus }
  48524. ]);
  48525. };
  48526. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48527. if (this._onLostFocus) {
  48528. BABYLON.Tools.UnregisterTopRootEvents([
  48529. { name: "blur", handler: this._onLostFocus }
  48530. ]);
  48531. }
  48532. if (element && this._observer) {
  48533. this.camera.getScene().onPointerObservable.remove(this._observer);
  48534. this._observer = null;
  48535. if (this._onContextMenu) {
  48536. element.removeEventListener("contextmenu", this._onContextMenu);
  48537. }
  48538. if (this._onMouseMove) {
  48539. element.removeEventListener("mousemove", this._onMouseMove);
  48540. }
  48541. if (this._onGestureStart) {
  48542. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48543. }
  48544. if (this._onGesture) {
  48545. element.removeEventListener("MSGestureChange", this._onGesture);
  48546. }
  48547. this._isPanClick = false;
  48548. this.pinchInwards = true;
  48549. this._onMouseMove = null;
  48550. this._onGestureStart = null;
  48551. this._onGesture = null;
  48552. this._MSGestureHandler = null;
  48553. this._onLostFocus = null;
  48554. this._onContextMenu = null;
  48555. }
  48556. };
  48557. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48558. return "ArcRotateCameraPointersInput";
  48559. };
  48560. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48561. return "pointers";
  48562. };
  48563. __decorate([
  48564. BABYLON.serialize()
  48565. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48566. __decorate([
  48567. BABYLON.serialize()
  48568. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48569. __decorate([
  48570. BABYLON.serialize()
  48571. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48572. __decorate([
  48573. BABYLON.serialize()
  48574. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48575. __decorate([
  48576. BABYLON.serialize()
  48577. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48578. __decorate([
  48579. BABYLON.serialize()
  48580. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48581. __decorate([
  48582. BABYLON.serialize()
  48583. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48584. __decorate([
  48585. BABYLON.serialize()
  48586. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48587. return ArcRotateCameraPointersInput;
  48588. }());
  48589. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48590. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48591. })(BABYLON || (BABYLON = {}));
  48592. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48593. var BABYLON;
  48594. (function (BABYLON) {
  48595. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48596. __extends(ArcRotateCameraInputsManager, _super);
  48597. function ArcRotateCameraInputsManager(camera) {
  48598. return _super.call(this, camera) || this;
  48599. }
  48600. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48601. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48602. return this;
  48603. };
  48604. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48605. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48606. return this;
  48607. };
  48608. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48609. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48610. return this;
  48611. };
  48612. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48613. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48614. return this;
  48615. };
  48616. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48617. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48618. return this;
  48619. };
  48620. return ArcRotateCameraInputsManager;
  48621. }(BABYLON.CameraInputsManager));
  48622. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48623. })(BABYLON || (BABYLON = {}));
  48624. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48625. var BABYLON;
  48626. (function (BABYLON) {
  48627. var ArcRotateCamera = /** @class */ (function (_super) {
  48628. __extends(ArcRotateCamera, _super);
  48629. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48630. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48631. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48632. _this.inertialAlphaOffset = 0;
  48633. _this.inertialBetaOffset = 0;
  48634. _this.inertialRadiusOffset = 0;
  48635. _this.lowerAlphaLimit = null;
  48636. _this.upperAlphaLimit = null;
  48637. _this.lowerBetaLimit = 0.01;
  48638. _this.upperBetaLimit = Math.PI;
  48639. _this.lowerRadiusLimit = null;
  48640. _this.upperRadiusLimit = null;
  48641. _this.inertialPanningX = 0;
  48642. _this.inertialPanningY = 0;
  48643. _this.pinchToPanMaxDistance = 20;
  48644. _this.panningDistanceLimit = null;
  48645. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48646. _this.panningInertia = 0.9;
  48647. //-- end properties for backward compatibility for inputs
  48648. _this.zoomOnFactor = 1;
  48649. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48650. _this.allowUpsideDown = true;
  48651. _this._viewMatrix = new BABYLON.Matrix();
  48652. // Panning
  48653. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48654. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48655. _this.checkCollisions = false;
  48656. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48657. _this._previousPosition = BABYLON.Vector3.Zero();
  48658. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48659. _this._newPosition = BABYLON.Vector3.Zero();
  48660. _this._computationVector = BABYLON.Vector3.Zero();
  48661. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48662. if (collidedMesh === void 0) { collidedMesh = null; }
  48663. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48664. newPosition.multiplyInPlace(_this._collider._radius);
  48665. }
  48666. if (!collidedMesh) {
  48667. _this._previousPosition.copyFrom(_this.position);
  48668. }
  48669. else {
  48670. _this.setPosition(newPosition);
  48671. if (_this.onCollide) {
  48672. _this.onCollide(collidedMesh);
  48673. }
  48674. }
  48675. // Recompute because of constraints
  48676. var cosa = Math.cos(_this.alpha);
  48677. var sina = Math.sin(_this.alpha);
  48678. var cosb = Math.cos(_this.beta);
  48679. var sinb = Math.sin(_this.beta);
  48680. if (sinb === 0) {
  48681. sinb = 0.0001;
  48682. }
  48683. var target = _this._getTargetPosition();
  48684. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48685. target.addToRef(_this._computationVector, _this._newPosition);
  48686. _this.position.copyFrom(_this._newPosition);
  48687. var up = _this.upVector;
  48688. if (_this.allowUpsideDown && _this.beta < 0) {
  48689. up = up.clone();
  48690. up = up.negate();
  48691. }
  48692. _this._computeViewMatrix(_this.position, target, up);
  48693. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48694. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48695. _this._collisionTriggered = false;
  48696. };
  48697. _this._target = BABYLON.Vector3.Zero();
  48698. if (target) {
  48699. _this.setTarget(target);
  48700. }
  48701. _this.alpha = alpha;
  48702. _this.beta = beta;
  48703. _this.radius = radius;
  48704. _this.getViewMatrix();
  48705. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48706. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48707. return _this;
  48708. }
  48709. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48710. get: function () {
  48711. return this._target;
  48712. },
  48713. set: function (value) {
  48714. this.setTarget(value);
  48715. },
  48716. enumerable: true,
  48717. configurable: true
  48718. });
  48719. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48720. //-- begin properties for backward compatibility for inputs
  48721. get: function () {
  48722. var pointers = this.inputs.attached["pointers"];
  48723. if (pointers)
  48724. return pointers.angularSensibilityX;
  48725. return 0;
  48726. },
  48727. set: function (value) {
  48728. var pointers = this.inputs.attached["pointers"];
  48729. if (pointers) {
  48730. pointers.angularSensibilityX = value;
  48731. }
  48732. },
  48733. enumerable: true,
  48734. configurable: true
  48735. });
  48736. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48737. get: function () {
  48738. var pointers = this.inputs.attached["pointers"];
  48739. if (pointers)
  48740. return pointers.angularSensibilityY;
  48741. return 0;
  48742. },
  48743. set: function (value) {
  48744. var pointers = this.inputs.attached["pointers"];
  48745. if (pointers) {
  48746. pointers.angularSensibilityY = value;
  48747. }
  48748. },
  48749. enumerable: true,
  48750. configurable: true
  48751. });
  48752. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48753. get: function () {
  48754. var pointers = this.inputs.attached["pointers"];
  48755. if (pointers)
  48756. return pointers.pinchPrecision;
  48757. return 0;
  48758. },
  48759. set: function (value) {
  48760. var pointers = this.inputs.attached["pointers"];
  48761. if (pointers) {
  48762. pointers.pinchPrecision = value;
  48763. }
  48764. },
  48765. enumerable: true,
  48766. configurable: true
  48767. });
  48768. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48769. get: function () {
  48770. var pointers = this.inputs.attached["pointers"];
  48771. if (pointers)
  48772. return pointers.pinchDeltaPercentage;
  48773. return 0;
  48774. },
  48775. set: function (value) {
  48776. var pointers = this.inputs.attached["pointers"];
  48777. if (pointers) {
  48778. pointers.pinchDeltaPercentage = value;
  48779. }
  48780. },
  48781. enumerable: true,
  48782. configurable: true
  48783. });
  48784. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48785. get: function () {
  48786. var pointers = this.inputs.attached["pointers"];
  48787. if (pointers)
  48788. return pointers.panningSensibility;
  48789. return 0;
  48790. },
  48791. set: function (value) {
  48792. var pointers = this.inputs.attached["pointers"];
  48793. if (pointers) {
  48794. pointers.panningSensibility = value;
  48795. }
  48796. },
  48797. enumerable: true,
  48798. configurable: true
  48799. });
  48800. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48801. get: function () {
  48802. var keyboard = this.inputs.attached["keyboard"];
  48803. if (keyboard)
  48804. return keyboard.keysUp;
  48805. return [];
  48806. },
  48807. set: function (value) {
  48808. var keyboard = this.inputs.attached["keyboard"];
  48809. if (keyboard)
  48810. keyboard.keysUp = value;
  48811. },
  48812. enumerable: true,
  48813. configurable: true
  48814. });
  48815. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48816. get: function () {
  48817. var keyboard = this.inputs.attached["keyboard"];
  48818. if (keyboard)
  48819. return keyboard.keysDown;
  48820. return [];
  48821. },
  48822. set: function (value) {
  48823. var keyboard = this.inputs.attached["keyboard"];
  48824. if (keyboard)
  48825. keyboard.keysDown = value;
  48826. },
  48827. enumerable: true,
  48828. configurable: true
  48829. });
  48830. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48831. get: function () {
  48832. var keyboard = this.inputs.attached["keyboard"];
  48833. if (keyboard)
  48834. return keyboard.keysLeft;
  48835. return [];
  48836. },
  48837. set: function (value) {
  48838. var keyboard = this.inputs.attached["keyboard"];
  48839. if (keyboard)
  48840. keyboard.keysLeft = value;
  48841. },
  48842. enumerable: true,
  48843. configurable: true
  48844. });
  48845. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48846. get: function () {
  48847. var keyboard = this.inputs.attached["keyboard"];
  48848. if (keyboard)
  48849. return keyboard.keysRight;
  48850. return [];
  48851. },
  48852. set: function (value) {
  48853. var keyboard = this.inputs.attached["keyboard"];
  48854. if (keyboard)
  48855. keyboard.keysRight = value;
  48856. },
  48857. enumerable: true,
  48858. configurable: true
  48859. });
  48860. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48861. get: function () {
  48862. var mousewheel = this.inputs.attached["mousewheel"];
  48863. if (mousewheel)
  48864. return mousewheel.wheelPrecision;
  48865. return 0;
  48866. },
  48867. set: function (value) {
  48868. var mousewheel = this.inputs.attached["mousewheel"];
  48869. if (mousewheel)
  48870. mousewheel.wheelPrecision = value;
  48871. },
  48872. enumerable: true,
  48873. configurable: true
  48874. });
  48875. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48876. get: function () {
  48877. var mousewheel = this.inputs.attached["mousewheel"];
  48878. if (mousewheel)
  48879. return mousewheel.wheelDeltaPercentage;
  48880. return 0;
  48881. },
  48882. set: function (value) {
  48883. var mousewheel = this.inputs.attached["mousewheel"];
  48884. if (mousewheel)
  48885. mousewheel.wheelDeltaPercentage = value;
  48886. },
  48887. enumerable: true,
  48888. configurable: true
  48889. });
  48890. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48891. get: function () {
  48892. return this._bouncingBehavior;
  48893. },
  48894. enumerable: true,
  48895. configurable: true
  48896. });
  48897. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48898. get: function () {
  48899. return this._bouncingBehavior != null;
  48900. },
  48901. set: function (value) {
  48902. if (value === this.useBouncingBehavior) {
  48903. return;
  48904. }
  48905. if (value) {
  48906. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48907. this.addBehavior(this._bouncingBehavior);
  48908. }
  48909. else if (this._bouncingBehavior) {
  48910. this.removeBehavior(this._bouncingBehavior);
  48911. this._bouncingBehavior = null;
  48912. }
  48913. },
  48914. enumerable: true,
  48915. configurable: true
  48916. });
  48917. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48918. get: function () {
  48919. return this._framingBehavior;
  48920. },
  48921. enumerable: true,
  48922. configurable: true
  48923. });
  48924. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48925. get: function () {
  48926. return this._framingBehavior != null;
  48927. },
  48928. set: function (value) {
  48929. if (value === this.useFramingBehavior) {
  48930. return;
  48931. }
  48932. if (value) {
  48933. this._framingBehavior = new BABYLON.FramingBehavior();
  48934. this.addBehavior(this._framingBehavior);
  48935. }
  48936. else if (this._framingBehavior) {
  48937. this.removeBehavior(this._framingBehavior);
  48938. this._framingBehavior = null;
  48939. }
  48940. },
  48941. enumerable: true,
  48942. configurable: true
  48943. });
  48944. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48945. get: function () {
  48946. return this._autoRotationBehavior;
  48947. },
  48948. enumerable: true,
  48949. configurable: true
  48950. });
  48951. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48952. get: function () {
  48953. return this._autoRotationBehavior != null;
  48954. },
  48955. set: function (value) {
  48956. if (value === this.useAutoRotationBehavior) {
  48957. return;
  48958. }
  48959. if (value) {
  48960. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48961. this.addBehavior(this._autoRotationBehavior);
  48962. }
  48963. else if (this._autoRotationBehavior) {
  48964. this.removeBehavior(this._autoRotationBehavior);
  48965. this._autoRotationBehavior = null;
  48966. }
  48967. },
  48968. enumerable: true,
  48969. configurable: true
  48970. });
  48971. // Cache
  48972. ArcRotateCamera.prototype._initCache = function () {
  48973. _super.prototype._initCache.call(this);
  48974. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48975. this._cache.alpha = undefined;
  48976. this._cache.beta = undefined;
  48977. this._cache.radius = undefined;
  48978. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48979. };
  48980. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48981. if (!ignoreParentClass) {
  48982. _super.prototype._updateCache.call(this);
  48983. }
  48984. this._cache._target.copyFrom(this._getTargetPosition());
  48985. this._cache.alpha = this.alpha;
  48986. this._cache.beta = this.beta;
  48987. this._cache.radius = this.radius;
  48988. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48989. };
  48990. ArcRotateCamera.prototype._getTargetPosition = function () {
  48991. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48992. var pos = this._targetHost.getAbsolutePosition();
  48993. if (this._targetBoundingCenter) {
  48994. pos.addToRef(this._targetBoundingCenter, this._target);
  48995. }
  48996. else {
  48997. this._target.copyFrom(pos);
  48998. }
  48999. }
  49000. var lockedTargetPosition = this._getLockedTargetPosition();
  49001. if (lockedTargetPosition) {
  49002. return lockedTargetPosition;
  49003. }
  49004. return this._target;
  49005. };
  49006. ArcRotateCamera.prototype.storeState = function () {
  49007. this._storedAlpha = this.alpha;
  49008. this._storedBeta = this.beta;
  49009. this._storedRadius = this.radius;
  49010. this._storedTarget = this._getTargetPosition().clone();
  49011. return _super.prototype.storeState.call(this);
  49012. };
  49013. /**
  49014. * Restored camera state. You must call storeState() first
  49015. */
  49016. ArcRotateCamera.prototype._restoreStateValues = function () {
  49017. if (!_super.prototype._restoreStateValues.call(this)) {
  49018. return false;
  49019. }
  49020. this.alpha = this._storedAlpha;
  49021. this.beta = this._storedBeta;
  49022. this.radius = this._storedRadius;
  49023. this.setTarget(this._storedTarget.clone());
  49024. this.inertialAlphaOffset = 0;
  49025. this.inertialBetaOffset = 0;
  49026. this.inertialRadiusOffset = 0;
  49027. this.inertialPanningX = 0;
  49028. this.inertialPanningY = 0;
  49029. return true;
  49030. };
  49031. // Synchronized
  49032. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49033. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49034. return false;
  49035. return this._cache._target.equals(this._getTargetPosition())
  49036. && this._cache.alpha === this.alpha
  49037. && this._cache.beta === this.beta
  49038. && this._cache.radius === this.radius
  49039. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49040. };
  49041. // Methods
  49042. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49043. var _this = this;
  49044. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49045. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49046. this._useCtrlForPanning = useCtrlForPanning;
  49047. this._panningMouseButton = panningMouseButton;
  49048. this.inputs.attachElement(element, noPreventDefault);
  49049. this._reset = function () {
  49050. _this.inertialAlphaOffset = 0;
  49051. _this.inertialBetaOffset = 0;
  49052. _this.inertialRadiusOffset = 0;
  49053. _this.inertialPanningX = 0;
  49054. _this.inertialPanningY = 0;
  49055. };
  49056. };
  49057. ArcRotateCamera.prototype.detachControl = function (element) {
  49058. this.inputs.detachElement(element);
  49059. if (this._reset) {
  49060. this._reset();
  49061. }
  49062. };
  49063. ArcRotateCamera.prototype._checkInputs = function () {
  49064. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49065. if (this._collisionTriggered) {
  49066. return;
  49067. }
  49068. this.inputs.checkInputs();
  49069. // Inertia
  49070. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49071. var inertialAlphaOffset = this.inertialAlphaOffset;
  49072. if (this.beta <= 0)
  49073. inertialAlphaOffset *= -1;
  49074. if (this.getScene().useRightHandedSystem)
  49075. inertialAlphaOffset *= -1;
  49076. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49077. inertialAlphaOffset *= -1;
  49078. this.alpha += inertialAlphaOffset;
  49079. this.beta += this.inertialBetaOffset;
  49080. this.radius -= this.inertialRadiusOffset;
  49081. this.inertialAlphaOffset *= this.inertia;
  49082. this.inertialBetaOffset *= this.inertia;
  49083. this.inertialRadiusOffset *= this.inertia;
  49084. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49085. this.inertialAlphaOffset = 0;
  49086. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49087. this.inertialBetaOffset = 0;
  49088. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49089. this.inertialRadiusOffset = 0;
  49090. }
  49091. // Panning inertia
  49092. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49093. if (!this._localDirection) {
  49094. this._localDirection = BABYLON.Vector3.Zero();
  49095. this._transformedDirection = BABYLON.Vector3.Zero();
  49096. }
  49097. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49098. this._localDirection.multiplyInPlace(this.panningAxis);
  49099. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49100. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49101. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49102. if (!this.panningAxis.y) {
  49103. this._transformedDirection.y = 0;
  49104. }
  49105. if (!this._targetHost) {
  49106. if (this.panningDistanceLimit) {
  49107. this._transformedDirection.addInPlace(this._target);
  49108. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49109. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49110. this._target.copyFrom(this._transformedDirection);
  49111. }
  49112. }
  49113. else {
  49114. this._target.addInPlace(this._transformedDirection);
  49115. }
  49116. }
  49117. this.inertialPanningX *= this.panningInertia;
  49118. this.inertialPanningY *= this.panningInertia;
  49119. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49120. this.inertialPanningX = 0;
  49121. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49122. this.inertialPanningY = 0;
  49123. }
  49124. // Limits
  49125. this._checkLimits();
  49126. _super.prototype._checkInputs.call(this);
  49127. };
  49128. ArcRotateCamera.prototype._checkLimits = function () {
  49129. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49130. if (this.allowUpsideDown && this.beta > Math.PI) {
  49131. this.beta = this.beta - (2 * Math.PI);
  49132. }
  49133. }
  49134. else {
  49135. if (this.beta < this.lowerBetaLimit) {
  49136. this.beta = this.lowerBetaLimit;
  49137. }
  49138. }
  49139. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49140. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49141. this.beta = this.beta + (2 * Math.PI);
  49142. }
  49143. }
  49144. else {
  49145. if (this.beta > this.upperBetaLimit) {
  49146. this.beta = this.upperBetaLimit;
  49147. }
  49148. }
  49149. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49150. this.alpha = this.lowerAlphaLimit;
  49151. }
  49152. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49153. this.alpha = this.upperAlphaLimit;
  49154. }
  49155. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49156. this.radius = this.lowerRadiusLimit;
  49157. }
  49158. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49159. this.radius = this.upperRadiusLimit;
  49160. }
  49161. };
  49162. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49163. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49164. this.radius = this._computationVector.length();
  49165. if (this.radius === 0) {
  49166. this.radius = 0.0001; // Just to avoid division by zero
  49167. }
  49168. // Alpha
  49169. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49170. if (this._computationVector.z < 0) {
  49171. this.alpha = 2 * Math.PI - this.alpha;
  49172. }
  49173. // Beta
  49174. this.beta = Math.acos(this._computationVector.y / this.radius);
  49175. this._checkLimits();
  49176. };
  49177. ArcRotateCamera.prototype.setPosition = function (position) {
  49178. if (this.position.equals(position)) {
  49179. return;
  49180. }
  49181. this.position.copyFrom(position);
  49182. this.rebuildAnglesAndRadius();
  49183. };
  49184. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49185. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49186. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49187. if (target.getBoundingInfo) {
  49188. if (toBoundingCenter) {
  49189. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49190. }
  49191. else {
  49192. this._targetBoundingCenter = null;
  49193. }
  49194. this._targetHost = target;
  49195. this._target = this._getTargetPosition();
  49196. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49197. }
  49198. else {
  49199. var newTarget = target;
  49200. var currentTarget = this._getTargetPosition();
  49201. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49202. return;
  49203. }
  49204. this._targetHost = null;
  49205. this._target = newTarget;
  49206. this._targetBoundingCenter = null;
  49207. this.onMeshTargetChangedObservable.notifyObservers(null);
  49208. }
  49209. this.rebuildAnglesAndRadius();
  49210. };
  49211. ArcRotateCamera.prototype._getViewMatrix = function () {
  49212. // Compute
  49213. var cosa = Math.cos(this.alpha);
  49214. var sina = Math.sin(this.alpha);
  49215. var cosb = Math.cos(this.beta);
  49216. var sinb = Math.sin(this.beta);
  49217. if (sinb === 0) {
  49218. sinb = 0.0001;
  49219. }
  49220. var target = this._getTargetPosition();
  49221. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49222. target.addToRef(this._computationVector, this._newPosition);
  49223. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49224. if (!this._collider) {
  49225. this._collider = new BABYLON.Collider();
  49226. }
  49227. this._collider._radius = this.collisionRadius;
  49228. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49229. this._collisionTriggered = true;
  49230. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49231. }
  49232. else {
  49233. this.position.copyFrom(this._newPosition);
  49234. var up = this.upVector;
  49235. if (this.allowUpsideDown && sinb < 0) {
  49236. up = up.clone();
  49237. up = up.negate();
  49238. }
  49239. this._computeViewMatrix(this.position, target, up);
  49240. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49241. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49242. }
  49243. this._currentTarget = target;
  49244. return this._viewMatrix;
  49245. };
  49246. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49247. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49248. meshes = meshes || this.getScene().meshes;
  49249. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49250. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49251. this.radius = distance * this.zoomOnFactor;
  49252. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49253. };
  49254. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49255. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49256. var meshesOrMinMaxVector;
  49257. var distance;
  49258. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49259. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49260. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49261. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49262. }
  49263. else { //minMaxVector and distance
  49264. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49265. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49266. distance = minMaxVectorAndDistance.distance;
  49267. }
  49268. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49269. if (!doNotUpdateMaxZ) {
  49270. this.maxZ = distance * 2;
  49271. }
  49272. };
  49273. /**
  49274. * @override
  49275. * Override Camera.createRigCamera
  49276. */
  49277. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49278. var alphaShift = 0;
  49279. switch (this.cameraRigMode) {
  49280. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49281. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49283. case BABYLON.Camera.RIG_MODE_VR:
  49284. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49285. break;
  49286. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49287. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49288. break;
  49289. }
  49290. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49291. rigCam._cameraRigParams = {};
  49292. return rigCam;
  49293. };
  49294. /**
  49295. * @override
  49296. * Override Camera._updateRigCameras
  49297. */
  49298. ArcRotateCamera.prototype._updateRigCameras = function () {
  49299. var camLeft = this._rigCameras[0];
  49300. var camRight = this._rigCameras[1];
  49301. camLeft.beta = camRight.beta = this.beta;
  49302. camLeft.radius = camRight.radius = this.radius;
  49303. switch (this.cameraRigMode) {
  49304. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49305. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49306. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49307. case BABYLON.Camera.RIG_MODE_VR:
  49308. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49309. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49310. break;
  49311. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49312. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49313. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49314. break;
  49315. }
  49316. _super.prototype._updateRigCameras.call(this);
  49317. };
  49318. ArcRotateCamera.prototype.dispose = function () {
  49319. this.inputs.clear();
  49320. _super.prototype.dispose.call(this);
  49321. };
  49322. ArcRotateCamera.prototype.getClassName = function () {
  49323. return "ArcRotateCamera";
  49324. };
  49325. __decorate([
  49326. BABYLON.serialize()
  49327. ], ArcRotateCamera.prototype, "alpha", void 0);
  49328. __decorate([
  49329. BABYLON.serialize()
  49330. ], ArcRotateCamera.prototype, "beta", void 0);
  49331. __decorate([
  49332. BABYLON.serialize()
  49333. ], ArcRotateCamera.prototype, "radius", void 0);
  49334. __decorate([
  49335. BABYLON.serializeAsVector3("target")
  49336. ], ArcRotateCamera.prototype, "_target", void 0);
  49337. __decorate([
  49338. BABYLON.serialize()
  49339. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49340. __decorate([
  49341. BABYLON.serialize()
  49342. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49343. __decorate([
  49344. BABYLON.serialize()
  49345. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49346. __decorate([
  49347. BABYLON.serialize()
  49348. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49349. __decorate([
  49350. BABYLON.serialize()
  49351. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49352. __decorate([
  49353. BABYLON.serialize()
  49354. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49355. __decorate([
  49356. BABYLON.serialize()
  49357. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49358. __decorate([
  49359. BABYLON.serialize()
  49360. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49361. __decorate([
  49362. BABYLON.serialize()
  49363. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49364. __decorate([
  49365. BABYLON.serialize()
  49366. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49367. __decorate([
  49368. BABYLON.serialize()
  49369. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49370. __decorate([
  49371. BABYLON.serialize()
  49372. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49373. __decorate([
  49374. BABYLON.serialize()
  49375. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49376. __decorate([
  49377. BABYLON.serializeAsVector3()
  49378. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49379. __decorate([
  49380. BABYLON.serialize()
  49381. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49382. __decorate([
  49383. BABYLON.serialize()
  49384. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49385. __decorate([
  49386. BABYLON.serialize()
  49387. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49388. return ArcRotateCamera;
  49389. }(BABYLON.TargetCamera));
  49390. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49391. })(BABYLON || (BABYLON = {}));
  49392. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49393. var BABYLON;
  49394. (function (BABYLON) {
  49395. /**
  49396. * The HemisphericLight simulates the ambient environment light,
  49397. * so the passed direction is the light reflection direction, not the incoming direction.
  49398. */
  49399. var HemisphericLight = /** @class */ (function (_super) {
  49400. __extends(HemisphericLight, _super);
  49401. /**
  49402. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49403. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49404. * The HemisphericLight can't cast shadows.
  49405. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49406. * @param name The friendly name of the light
  49407. * @param direction The direction of the light reflection
  49408. * @param scene The scene the light belongs to
  49409. */
  49410. function HemisphericLight(name, direction, scene) {
  49411. var _this = _super.call(this, name, scene) || this;
  49412. /**
  49413. * The groundColor is the light in the opposite direction to the one specified during creation.
  49414. * 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.
  49415. */
  49416. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49417. _this.direction = direction || BABYLON.Vector3.Up();
  49418. return _this;
  49419. }
  49420. HemisphericLight.prototype._buildUniformLayout = function () {
  49421. this._uniformBuffer.addUniform("vLightData", 4);
  49422. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49423. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49424. this._uniformBuffer.addUniform("vLightGround", 3);
  49425. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49426. this._uniformBuffer.addUniform("depthValues", 2);
  49427. this._uniformBuffer.create();
  49428. };
  49429. /**
  49430. * Returns the string "HemisphericLight".
  49431. * @return The class name
  49432. */
  49433. HemisphericLight.prototype.getClassName = function () {
  49434. return "HemisphericLight";
  49435. };
  49436. /**
  49437. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49438. * Returns the updated direction.
  49439. * @param target The target the direction should point to
  49440. * @return The computed direction
  49441. */
  49442. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49443. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49444. return this.direction;
  49445. };
  49446. /**
  49447. * Returns the shadow generator associated to the light.
  49448. * @returns Always null for hemispheric lights because it does not support shadows.
  49449. */
  49450. HemisphericLight.prototype.getShadowGenerator = function () {
  49451. return null;
  49452. };
  49453. /**
  49454. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49455. * @param effect The effect to update
  49456. * @param lightIndex The index of the light in the effect to update
  49457. * @returns The hemispheric light
  49458. */
  49459. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49460. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49461. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49462. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49463. return this;
  49464. };
  49465. /**
  49466. * @hidden internal use only.
  49467. */
  49468. HemisphericLight.prototype._getWorldMatrix = function () {
  49469. if (!this._worldMatrix) {
  49470. this._worldMatrix = BABYLON.Matrix.Identity();
  49471. }
  49472. return this._worldMatrix;
  49473. };
  49474. /**
  49475. * Returns the integer 3.
  49476. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49477. */
  49478. HemisphericLight.prototype.getTypeID = function () {
  49479. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49480. };
  49481. __decorate([
  49482. BABYLON.serializeAsColor3()
  49483. ], HemisphericLight.prototype, "groundColor", void 0);
  49484. __decorate([
  49485. BABYLON.serializeAsVector3()
  49486. ], HemisphericLight.prototype, "direction", void 0);
  49487. return HemisphericLight;
  49488. }(BABYLON.Light));
  49489. BABYLON.HemisphericLight = HemisphericLight;
  49490. })(BABYLON || (BABYLON = {}));
  49491. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49492. var BABYLON;
  49493. (function (BABYLON) {
  49494. /**
  49495. * Base implementation IShadowLight
  49496. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49497. */
  49498. var ShadowLight = /** @class */ (function (_super) {
  49499. __extends(ShadowLight, _super);
  49500. function ShadowLight() {
  49501. var _this = _super !== null && _super.apply(this, arguments) || this;
  49502. _this._needProjectionMatrixCompute = true;
  49503. return _this;
  49504. }
  49505. ShadowLight.prototype._setPosition = function (value) {
  49506. this._position = value;
  49507. };
  49508. Object.defineProperty(ShadowLight.prototype, "position", {
  49509. /**
  49510. * Sets the position the shadow will be casted from. Also use as the light position for both
  49511. * point and spot lights.
  49512. */
  49513. get: function () {
  49514. return this._position;
  49515. },
  49516. /**
  49517. * Sets the position the shadow will be casted from. Also use as the light position for both
  49518. * point and spot lights.
  49519. */
  49520. set: function (value) {
  49521. this._setPosition(value);
  49522. },
  49523. enumerable: true,
  49524. configurable: true
  49525. });
  49526. ShadowLight.prototype._setDirection = function (value) {
  49527. this._direction = value;
  49528. };
  49529. Object.defineProperty(ShadowLight.prototype, "direction", {
  49530. /**
  49531. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49532. * Also use as the light direction on spot and directional lights.
  49533. */
  49534. get: function () {
  49535. return this._direction;
  49536. },
  49537. /**
  49538. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49539. * Also use as the light direction on spot and directional lights.
  49540. */
  49541. set: function (value) {
  49542. this._setDirection(value);
  49543. },
  49544. enumerable: true,
  49545. configurable: true
  49546. });
  49547. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49548. /**
  49549. * Gets the shadow projection clipping minimum z value.
  49550. */
  49551. get: function () {
  49552. return this._shadowMinZ;
  49553. },
  49554. /**
  49555. * Sets the shadow projection clipping minimum z value.
  49556. */
  49557. set: function (value) {
  49558. this._shadowMinZ = value;
  49559. this.forceProjectionMatrixCompute();
  49560. },
  49561. enumerable: true,
  49562. configurable: true
  49563. });
  49564. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49565. /**
  49566. * Sets the shadow projection clipping maximum z value.
  49567. */
  49568. get: function () {
  49569. return this._shadowMaxZ;
  49570. },
  49571. /**
  49572. * Gets the shadow projection clipping maximum z value.
  49573. */
  49574. set: function (value) {
  49575. this._shadowMaxZ = value;
  49576. this.forceProjectionMatrixCompute();
  49577. },
  49578. enumerable: true,
  49579. configurable: true
  49580. });
  49581. /**
  49582. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49583. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49584. */
  49585. ShadowLight.prototype.computeTransformedInformation = function () {
  49586. if (this.parent && this.parent.getWorldMatrix) {
  49587. if (!this.transformedPosition) {
  49588. this.transformedPosition = BABYLON.Vector3.Zero();
  49589. }
  49590. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49591. // In case the direction is present.
  49592. if (this.direction) {
  49593. if (!this.transformedDirection) {
  49594. this.transformedDirection = BABYLON.Vector3.Zero();
  49595. }
  49596. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49597. }
  49598. return true;
  49599. }
  49600. return false;
  49601. };
  49602. /**
  49603. * Return the depth scale used for the shadow map.
  49604. * @returns the depth scale.
  49605. */
  49606. ShadowLight.prototype.getDepthScale = function () {
  49607. return 50.0;
  49608. };
  49609. /**
  49610. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49611. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49612. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49613. */
  49614. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49615. return this.transformedDirection ? this.transformedDirection : this.direction;
  49616. };
  49617. /**
  49618. * Returns the ShadowLight absolute position in the World.
  49619. * @returns the position vector in world space
  49620. */
  49621. ShadowLight.prototype.getAbsolutePosition = function () {
  49622. return this.transformedPosition ? this.transformedPosition : this.position;
  49623. };
  49624. /**
  49625. * Sets the ShadowLight direction toward the passed target.
  49626. * @param target The point tot target in local space
  49627. * @returns the updated ShadowLight direction
  49628. */
  49629. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49630. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49631. return this.direction;
  49632. };
  49633. /**
  49634. * Returns the light rotation in euler definition.
  49635. * @returns the x y z rotation in local space.
  49636. */
  49637. ShadowLight.prototype.getRotation = function () {
  49638. this.direction.normalize();
  49639. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49640. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49641. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49642. };
  49643. /**
  49644. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49645. * @returns true if a cube texture needs to be use
  49646. */
  49647. ShadowLight.prototype.needCube = function () {
  49648. return false;
  49649. };
  49650. /**
  49651. * Detects if the projection matrix requires to be recomputed this frame.
  49652. * @returns true if it requires to be recomputed otherwise, false.
  49653. */
  49654. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49655. return this._needProjectionMatrixCompute;
  49656. };
  49657. /**
  49658. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49659. */
  49660. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49661. this._needProjectionMatrixCompute = true;
  49662. };
  49663. /**
  49664. * Get the world matrix of the sahdow lights.
  49665. * @hidden Internal Use Only
  49666. */
  49667. ShadowLight.prototype._getWorldMatrix = function () {
  49668. if (!this._worldMatrix) {
  49669. this._worldMatrix = BABYLON.Matrix.Identity();
  49670. }
  49671. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49672. return this._worldMatrix;
  49673. };
  49674. /**
  49675. * Gets the minZ used for shadow according to both the scene and the light.
  49676. * @param activeCamera The camera we are returning the min for
  49677. * @returns the depth min z
  49678. */
  49679. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49680. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49681. };
  49682. /**
  49683. * Gets the maxZ used for shadow according to both the scene and the light.
  49684. * @param activeCamera The camera we are returning the max for
  49685. * @returns the depth max z
  49686. */
  49687. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49688. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49689. };
  49690. /**
  49691. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49692. * @param matrix The materix to updated with the projection information
  49693. * @param viewMatrix The transform matrix of the light
  49694. * @param renderList The list of mesh to render in the map
  49695. * @returns The current light
  49696. */
  49697. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49698. if (this.customProjectionMatrixBuilder) {
  49699. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49700. }
  49701. else {
  49702. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49703. }
  49704. return this;
  49705. };
  49706. __decorate([
  49707. BABYLON.serializeAsVector3()
  49708. ], ShadowLight.prototype, "position", null);
  49709. __decorate([
  49710. BABYLON.serializeAsVector3()
  49711. ], ShadowLight.prototype, "direction", null);
  49712. __decorate([
  49713. BABYLON.serialize()
  49714. ], ShadowLight.prototype, "shadowMinZ", null);
  49715. __decorate([
  49716. BABYLON.serialize()
  49717. ], ShadowLight.prototype, "shadowMaxZ", null);
  49718. return ShadowLight;
  49719. }(BABYLON.Light));
  49720. BABYLON.ShadowLight = ShadowLight;
  49721. })(BABYLON || (BABYLON = {}));
  49722. //# sourceMappingURL=babylon.shadowLight.js.map
  49723. var BABYLON;
  49724. (function (BABYLON) {
  49725. /**
  49726. * A point light is a light defined by an unique point in world space.
  49727. * The light is emitted in every direction from this point.
  49728. * A good example of a point light is a standard light bulb.
  49729. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49730. */
  49731. var PointLight = /** @class */ (function (_super) {
  49732. __extends(PointLight, _super);
  49733. /**
  49734. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49735. * A PointLight emits the light in every direction.
  49736. * It can cast shadows.
  49737. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49738. * ```javascript
  49739. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49740. * ```
  49741. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49742. * @param name The light friendly name
  49743. * @param position The position of the point light in the scene
  49744. * @param scene The scene the lights belongs to
  49745. */
  49746. function PointLight(name, position, scene) {
  49747. var _this = _super.call(this, name, scene) || this;
  49748. _this._shadowAngle = Math.PI / 2;
  49749. _this.position = position;
  49750. return _this;
  49751. }
  49752. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49753. /**
  49754. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49755. * This specifies what angle the shadow will use to be created.
  49756. *
  49757. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49758. */
  49759. get: function () {
  49760. return this._shadowAngle;
  49761. },
  49762. /**
  49763. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49764. * This specifies what angle the shadow will use to be created.
  49765. *
  49766. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49767. */
  49768. set: function (value) {
  49769. this._shadowAngle = value;
  49770. this.forceProjectionMatrixCompute();
  49771. },
  49772. enumerable: true,
  49773. configurable: true
  49774. });
  49775. Object.defineProperty(PointLight.prototype, "direction", {
  49776. /**
  49777. * Gets the direction if it has been set.
  49778. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49779. */
  49780. get: function () {
  49781. return this._direction;
  49782. },
  49783. /**
  49784. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49785. */
  49786. set: function (value) {
  49787. var previousNeedCube = this.needCube();
  49788. this._direction = value;
  49789. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49790. this._shadowGenerator.recreateShadowMap();
  49791. }
  49792. },
  49793. enumerable: true,
  49794. configurable: true
  49795. });
  49796. /**
  49797. * Returns the string "PointLight"
  49798. * @returns the class name
  49799. */
  49800. PointLight.prototype.getClassName = function () {
  49801. return "PointLight";
  49802. };
  49803. /**
  49804. * Returns the integer 0.
  49805. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49806. */
  49807. PointLight.prototype.getTypeID = function () {
  49808. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49809. };
  49810. /**
  49811. * Specifies wether or not the shadowmap should be a cube texture.
  49812. * @returns true if the shadowmap needs to be a cube texture.
  49813. */
  49814. PointLight.prototype.needCube = function () {
  49815. return !this.direction;
  49816. };
  49817. /**
  49818. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49819. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49820. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49821. */
  49822. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49823. if (this.direction) {
  49824. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49825. }
  49826. else {
  49827. switch (faceIndex) {
  49828. case 0:
  49829. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49830. case 1:
  49831. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49832. case 2:
  49833. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49834. case 3:
  49835. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49836. case 4:
  49837. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49838. case 5:
  49839. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49840. }
  49841. }
  49842. return BABYLON.Vector3.Zero();
  49843. };
  49844. /**
  49845. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49846. * - fov = PI / 2
  49847. * - aspect ratio : 1.0
  49848. * - z-near and far equal to the active camera minZ and maxZ.
  49849. * Returns the PointLight.
  49850. */
  49851. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49852. var activeCamera = this.getScene().activeCamera;
  49853. if (!activeCamera) {
  49854. return;
  49855. }
  49856. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49857. };
  49858. PointLight.prototype._buildUniformLayout = function () {
  49859. this._uniformBuffer.addUniform("vLightData", 4);
  49860. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49861. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49862. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49863. this._uniformBuffer.addUniform("depthValues", 2);
  49864. this._uniformBuffer.create();
  49865. };
  49866. /**
  49867. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49868. * @param effect The effect to update
  49869. * @param lightIndex The index of the light in the effect to update
  49870. * @returns The point light
  49871. */
  49872. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49873. if (this.computeTransformedInformation()) {
  49874. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49875. return this;
  49876. }
  49877. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49878. return this;
  49879. };
  49880. __decorate([
  49881. BABYLON.serialize()
  49882. ], PointLight.prototype, "shadowAngle", null);
  49883. return PointLight;
  49884. }(BABYLON.ShadowLight));
  49885. BABYLON.PointLight = PointLight;
  49886. })(BABYLON || (BABYLON = {}));
  49887. //# sourceMappingURL=babylon.pointLight.js.map
  49888. var BABYLON;
  49889. (function (BABYLON) {
  49890. /**
  49891. * A directional light is defined by a direction (what a surprise!).
  49892. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49893. * 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.
  49894. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49895. */
  49896. var DirectionalLight = /** @class */ (function (_super) {
  49897. __extends(DirectionalLight, _super);
  49898. /**
  49899. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49900. * The directional light is emitted from everywhere in the given direction.
  49901. * It can cast shawdows.
  49902. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49903. * @param name The friendly name of the light
  49904. * @param direction The direction of the light
  49905. * @param scene The scene the light belongs to
  49906. */
  49907. function DirectionalLight(name, direction, scene) {
  49908. var _this = _super.call(this, name, scene) || this;
  49909. _this._shadowFrustumSize = 0;
  49910. _this._shadowOrthoScale = 0.1;
  49911. /**
  49912. * Automatically compute the projection matrix to best fit (including all the casters)
  49913. * on each frame.
  49914. */
  49915. _this.autoUpdateExtends = true;
  49916. // Cache
  49917. _this._orthoLeft = Number.MAX_VALUE;
  49918. _this._orthoRight = Number.MIN_VALUE;
  49919. _this._orthoTop = Number.MIN_VALUE;
  49920. _this._orthoBottom = Number.MAX_VALUE;
  49921. _this.position = direction.scale(-1.0);
  49922. _this.direction = direction;
  49923. return _this;
  49924. }
  49925. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49926. /**
  49927. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49928. */
  49929. get: function () {
  49930. return this._shadowFrustumSize;
  49931. },
  49932. /**
  49933. * Specifies a fix frustum size for the shadow generation.
  49934. */
  49935. set: function (value) {
  49936. this._shadowFrustumSize = value;
  49937. this.forceProjectionMatrixCompute();
  49938. },
  49939. enumerable: true,
  49940. configurable: true
  49941. });
  49942. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49943. /**
  49944. * Gets the shadow projection scale against the optimal computed one.
  49945. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49946. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49947. */
  49948. get: function () {
  49949. return this._shadowOrthoScale;
  49950. },
  49951. /**
  49952. * Sets the shadow projection scale against the optimal computed one.
  49953. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49954. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49955. */
  49956. set: function (value) {
  49957. this._shadowOrthoScale = value;
  49958. this.forceProjectionMatrixCompute();
  49959. },
  49960. enumerable: true,
  49961. configurable: true
  49962. });
  49963. /**
  49964. * Returns the string "DirectionalLight".
  49965. * @return The class name
  49966. */
  49967. DirectionalLight.prototype.getClassName = function () {
  49968. return "DirectionalLight";
  49969. };
  49970. /**
  49971. * Returns the integer 1.
  49972. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49973. */
  49974. DirectionalLight.prototype.getTypeID = function () {
  49975. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49976. };
  49977. /**
  49978. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49979. * Returns the DirectionalLight Shadow projection matrix.
  49980. */
  49981. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49982. if (this.shadowFrustumSize > 0) {
  49983. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49984. }
  49985. else {
  49986. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49987. }
  49988. };
  49989. /**
  49990. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49991. * Returns the DirectionalLight Shadow projection matrix.
  49992. */
  49993. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49994. var activeCamera = this.getScene().activeCamera;
  49995. if (!activeCamera) {
  49996. return;
  49997. }
  49998. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49999. };
  50000. /**
  50001. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50002. * Returns the DirectionalLight Shadow projection matrix.
  50003. */
  50004. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50005. var activeCamera = this.getScene().activeCamera;
  50006. if (!activeCamera) {
  50007. return;
  50008. }
  50009. // Check extends
  50010. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50011. var tempVector3 = BABYLON.Vector3.Zero();
  50012. this._orthoLeft = Number.MAX_VALUE;
  50013. this._orthoRight = Number.MIN_VALUE;
  50014. this._orthoTop = Number.MIN_VALUE;
  50015. this._orthoBottom = Number.MAX_VALUE;
  50016. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50017. var mesh = renderList[meshIndex];
  50018. if (!mesh) {
  50019. continue;
  50020. }
  50021. var boundingInfo = mesh.getBoundingInfo();
  50022. var boundingBox = boundingInfo.boundingBox;
  50023. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50024. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50025. if (tempVector3.x < this._orthoLeft)
  50026. this._orthoLeft = tempVector3.x;
  50027. if (tempVector3.y < this._orthoBottom)
  50028. this._orthoBottom = tempVector3.y;
  50029. if (tempVector3.x > this._orthoRight)
  50030. this._orthoRight = tempVector3.x;
  50031. if (tempVector3.y > this._orthoTop)
  50032. this._orthoTop = tempVector3.y;
  50033. }
  50034. }
  50035. }
  50036. var xOffset = this._orthoRight - this._orthoLeft;
  50037. var yOffset = this._orthoTop - this._orthoBottom;
  50038. 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);
  50039. };
  50040. DirectionalLight.prototype._buildUniformLayout = function () {
  50041. this._uniformBuffer.addUniform("vLightData", 4);
  50042. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50043. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50044. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50045. this._uniformBuffer.addUniform("depthValues", 2);
  50046. this._uniformBuffer.create();
  50047. };
  50048. /**
  50049. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50050. * @param effect The effect to update
  50051. * @param lightIndex The index of the light in the effect to update
  50052. * @returns The directional light
  50053. */
  50054. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50055. if (this.computeTransformedInformation()) {
  50056. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50057. return this;
  50058. }
  50059. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50060. return this;
  50061. };
  50062. /**
  50063. * Gets the minZ used for shadow according to both the scene and the light.
  50064. *
  50065. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50066. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50067. * @param activeCamera The camera we are returning the min for
  50068. * @returns the depth min z
  50069. */
  50070. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50071. return 1;
  50072. };
  50073. /**
  50074. * Gets the maxZ used for shadow according to both the scene and the light.
  50075. *
  50076. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50077. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50078. * @param activeCamera The camera we are returning the max for
  50079. * @returns the depth max z
  50080. */
  50081. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50082. return 1;
  50083. };
  50084. __decorate([
  50085. BABYLON.serialize()
  50086. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50087. __decorate([
  50088. BABYLON.serialize()
  50089. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50090. __decorate([
  50091. BABYLON.serialize()
  50092. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50093. return DirectionalLight;
  50094. }(BABYLON.ShadowLight));
  50095. BABYLON.DirectionalLight = DirectionalLight;
  50096. })(BABYLON || (BABYLON = {}));
  50097. //# sourceMappingURL=babylon.directionalLight.js.map
  50098. var BABYLON;
  50099. (function (BABYLON) {
  50100. /**
  50101. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50102. * These values define a cone of light starting from the position, emitting toward the direction.
  50103. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50104. * and the exponent defines the speed of the decay of the light with distance (reach).
  50105. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50106. */
  50107. var SpotLight = /** @class */ (function (_super) {
  50108. __extends(SpotLight, _super);
  50109. /**
  50110. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50111. * It can cast shadows.
  50112. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50113. * @param name The light friendly name
  50114. * @param position The position of the spot light in the scene
  50115. * @param direction The direction of the light in the scene
  50116. * @param angle The cone angle of the light in Radians
  50117. * @param exponent The light decay speed with the distance from the emission spot
  50118. * @param scene The scene the lights belongs to
  50119. */
  50120. function SpotLight(name, position, direction, angle, exponent, scene) {
  50121. var _this = _super.call(this, name, scene) || this;
  50122. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50123. _this._projectionTextureLightNear = 1e-6;
  50124. _this._projectionTextureLightFar = 1000.0;
  50125. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50126. _this._projectionTextureViewLightDirty = true;
  50127. _this._projectionTextureProjectionLightDirty = true;
  50128. _this._projectionTextureDirty = true;
  50129. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50130. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50131. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50132. _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);
  50133. _this.position = position;
  50134. _this.direction = direction;
  50135. _this.angle = angle;
  50136. _this.exponent = exponent;
  50137. return _this;
  50138. }
  50139. Object.defineProperty(SpotLight.prototype, "angle", {
  50140. /**
  50141. * Gets the cone angle of the spot light in Radians.
  50142. */
  50143. get: function () {
  50144. return this._angle;
  50145. },
  50146. /**
  50147. * Sets the cone angle of the spot light in Radians.
  50148. */
  50149. set: function (value) {
  50150. this._angle = value;
  50151. this._projectionTextureProjectionLightDirty = true;
  50152. this.forceProjectionMatrixCompute();
  50153. },
  50154. enumerable: true,
  50155. configurable: true
  50156. });
  50157. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50158. /**
  50159. * Allows scaling the angle of the light for shadow generation only.
  50160. */
  50161. get: function () {
  50162. return this._shadowAngleScale;
  50163. },
  50164. /**
  50165. * Allows scaling the angle of the light for shadow generation only.
  50166. */
  50167. set: function (value) {
  50168. this._shadowAngleScale = value;
  50169. this.forceProjectionMatrixCompute();
  50170. },
  50171. enumerable: true,
  50172. configurable: true
  50173. });
  50174. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50175. /**
  50176. * Allows reading the projecton texture
  50177. */
  50178. get: function () {
  50179. return this._projectionTextureMatrix;
  50180. },
  50181. enumerable: true,
  50182. configurable: true
  50183. });
  50184. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50185. /**
  50186. * Gets the near clip of the Spotlight for texture projection.
  50187. */
  50188. get: function () {
  50189. return this._projectionTextureLightNear;
  50190. },
  50191. /**
  50192. * Sets the near clip of the Spotlight for texture projection.
  50193. */
  50194. set: function (value) {
  50195. this._projectionTextureLightNear = value;
  50196. this._projectionTextureProjectionLightDirty = true;
  50197. },
  50198. enumerable: true,
  50199. configurable: true
  50200. });
  50201. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50202. /**
  50203. * Gets the far clip of the Spotlight for texture projection.
  50204. */
  50205. get: function () {
  50206. return this._projectionTextureLightFar;
  50207. },
  50208. /**
  50209. * Sets the far clip of the Spotlight for texture projection.
  50210. */
  50211. set: function (value) {
  50212. this._projectionTextureLightFar = value;
  50213. this._projectionTextureProjectionLightDirty = true;
  50214. },
  50215. enumerable: true,
  50216. configurable: true
  50217. });
  50218. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50219. /**
  50220. * Gets the Up vector of the Spotlight for texture projection.
  50221. */
  50222. get: function () {
  50223. return this._projectionTextureUpDirection;
  50224. },
  50225. /**
  50226. * Sets the Up vector of the Spotlight for texture projection.
  50227. */
  50228. set: function (value) {
  50229. this._projectionTextureUpDirection = value;
  50230. this._projectionTextureProjectionLightDirty = true;
  50231. },
  50232. enumerable: true,
  50233. configurable: true
  50234. });
  50235. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50236. /**
  50237. * Gets the projection texture of the light.
  50238. */
  50239. get: function () {
  50240. return this._projectionTexture;
  50241. },
  50242. /**
  50243. * Sets the projection texture of the light.
  50244. */
  50245. set: function (value) {
  50246. this._projectionTexture = value;
  50247. this._projectionTextureDirty = true;
  50248. },
  50249. enumerable: true,
  50250. configurable: true
  50251. });
  50252. /**
  50253. * Returns the string "SpotLight".
  50254. * @returns the class name
  50255. */
  50256. SpotLight.prototype.getClassName = function () {
  50257. return "SpotLight";
  50258. };
  50259. /**
  50260. * Returns the integer 2.
  50261. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50262. */
  50263. SpotLight.prototype.getTypeID = function () {
  50264. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50265. };
  50266. /**
  50267. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50268. */
  50269. SpotLight.prototype._setDirection = function (value) {
  50270. _super.prototype._setDirection.call(this, value);
  50271. this._projectionTextureViewLightDirty = true;
  50272. };
  50273. /**
  50274. * Overrides the position setter to recompute the projection texture view light Matrix.
  50275. */
  50276. SpotLight.prototype._setPosition = function (value) {
  50277. _super.prototype._setPosition.call(this, value);
  50278. this._projectionTextureViewLightDirty = true;
  50279. };
  50280. /**
  50281. * 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.
  50282. * Returns the SpotLight.
  50283. */
  50284. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50285. var activeCamera = this.getScene().activeCamera;
  50286. if (!activeCamera) {
  50287. return;
  50288. }
  50289. this._shadowAngleScale = this._shadowAngleScale || 1;
  50290. var angle = this._shadowAngleScale * this._angle;
  50291. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50292. };
  50293. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50294. this._projectionTextureViewLightDirty = false;
  50295. this._projectionTextureDirty = true;
  50296. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50297. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50298. };
  50299. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50300. this._projectionTextureProjectionLightDirty = false;
  50301. this._projectionTextureDirty = true;
  50302. var light_far = this.projectionTextureLightFar;
  50303. var light_near = this.projectionTextureLightNear;
  50304. var P = light_far / (light_far - light_near);
  50305. var Q = -P * light_near;
  50306. var S = 1.0 / Math.tan(this._angle / 2.0);
  50307. var A = 1.0;
  50308. 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);
  50309. };
  50310. /**
  50311. * Main function for light texture projection matrix computing.
  50312. */
  50313. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50314. this._projectionTextureDirty = false;
  50315. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50316. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50317. };
  50318. SpotLight.prototype._buildUniformLayout = function () {
  50319. this._uniformBuffer.addUniform("vLightData", 4);
  50320. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50321. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50322. this._uniformBuffer.addUniform("vLightDirection", 3);
  50323. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50324. this._uniformBuffer.addUniform("depthValues", 2);
  50325. this._uniformBuffer.create();
  50326. };
  50327. /**
  50328. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50329. * @param effect The effect to update
  50330. * @param lightIndex The index of the light in the effect to update
  50331. * @returns The spot light
  50332. */
  50333. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50334. var normalizeDirection;
  50335. if (this.computeTransformedInformation()) {
  50336. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50337. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50338. }
  50339. else {
  50340. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50341. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50342. }
  50343. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50344. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50345. if (this._projectionTextureViewLightDirty) {
  50346. this._computeProjectionTextureViewLightMatrix();
  50347. }
  50348. if (this._projectionTextureProjectionLightDirty) {
  50349. this._computeProjectionTextureProjectionLightMatrix();
  50350. }
  50351. if (this._projectionTextureDirty) {
  50352. this._computeProjectionTextureMatrix();
  50353. }
  50354. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50355. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50356. }
  50357. return this;
  50358. };
  50359. /**
  50360. * Disposes the light and the associated resources.
  50361. */
  50362. SpotLight.prototype.dispose = function () {
  50363. _super.prototype.dispose.call(this);
  50364. if (this._projectionTexture) {
  50365. this._projectionTexture.dispose();
  50366. }
  50367. };
  50368. __decorate([
  50369. BABYLON.serialize()
  50370. ], SpotLight.prototype, "angle", null);
  50371. __decorate([
  50372. BABYLON.serialize()
  50373. ], SpotLight.prototype, "shadowAngleScale", null);
  50374. __decorate([
  50375. BABYLON.serialize()
  50376. ], SpotLight.prototype, "exponent", void 0);
  50377. __decorate([
  50378. BABYLON.serialize()
  50379. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50380. __decorate([
  50381. BABYLON.serialize()
  50382. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50383. __decorate([
  50384. BABYLON.serialize()
  50385. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50386. __decorate([
  50387. BABYLON.serializeAsTexture("projectedLightTexture")
  50388. ], SpotLight.prototype, "_projectionTexture", void 0);
  50389. return SpotLight;
  50390. }(BABYLON.ShadowLight));
  50391. BABYLON.SpotLight = SpotLight;
  50392. })(BABYLON || (BABYLON = {}));
  50393. //# sourceMappingURL=babylon.spotLight.js.map
  50394. var BABYLON;
  50395. (function (BABYLON) {
  50396. /**
  50397. * Class used to override all child animations of a given target
  50398. */
  50399. var AnimationPropertiesOverride = /** @class */ (function () {
  50400. function AnimationPropertiesOverride() {
  50401. /**
  50402. * Gets or sets a value indicating if animation blending must be used
  50403. */
  50404. this.enableBlending = false;
  50405. /**
  50406. * Gets or sets the blending speed to use when enableBlending is true
  50407. */
  50408. this.blendingSpeed = 0.01;
  50409. /**
  50410. * Gets or sets the default loop mode to use
  50411. */
  50412. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50413. }
  50414. return AnimationPropertiesOverride;
  50415. }());
  50416. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50417. })(BABYLON || (BABYLON = {}));
  50418. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50419. var BABYLON;
  50420. (function (BABYLON) {
  50421. /**
  50422. * Represents the range of an animation
  50423. */
  50424. var AnimationRange = /** @class */ (function () {
  50425. /**
  50426. * Initializes the range of an animation
  50427. * @param name The name of the animation range
  50428. * @param from The starting frame of the animation
  50429. * @param to The ending frame of the animation
  50430. */
  50431. function AnimationRange(
  50432. /**The name of the animation range**/
  50433. name,
  50434. /**The starting frame of the animation */
  50435. from,
  50436. /**The ending frame of the animation*/
  50437. to) {
  50438. this.name = name;
  50439. this.from = from;
  50440. this.to = to;
  50441. }
  50442. /**
  50443. * Makes a copy of the animation range
  50444. * @returns A copy of the animation range
  50445. */
  50446. AnimationRange.prototype.clone = function () {
  50447. return new AnimationRange(this.name, this.from, this.to);
  50448. };
  50449. return AnimationRange;
  50450. }());
  50451. BABYLON.AnimationRange = AnimationRange;
  50452. /**
  50453. * Composed of a frame, and an action function
  50454. */
  50455. var AnimationEvent = /** @class */ (function () {
  50456. /**
  50457. * Initializes the animation event
  50458. * @param frame The frame for which the event is triggered
  50459. * @param action The event to perform when triggered
  50460. * @param onlyOnce Specifies if the event should be triggered only once
  50461. */
  50462. function AnimationEvent(
  50463. /** The frame for which the event is triggered **/
  50464. frame,
  50465. /** The event to perform when triggered **/
  50466. action,
  50467. /** Specifies if the event should be triggered only once**/
  50468. onlyOnce) {
  50469. this.frame = frame;
  50470. this.action = action;
  50471. this.onlyOnce = onlyOnce;
  50472. /**
  50473. * Specifies if the animation event is done
  50474. */
  50475. this.isDone = false;
  50476. }
  50477. /** @hidden */
  50478. AnimationEvent.prototype._clone = function () {
  50479. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50480. };
  50481. return AnimationEvent;
  50482. }());
  50483. BABYLON.AnimationEvent = AnimationEvent;
  50484. /**
  50485. * A cursor which tracks a point on a path
  50486. */
  50487. var PathCursor = /** @class */ (function () {
  50488. /**
  50489. * Initializes the path cursor
  50490. * @param path The path to track
  50491. */
  50492. function PathCursor(path) {
  50493. this.path = path;
  50494. /**
  50495. * Stores path cursor callbacks for when an onchange event is triggered
  50496. */
  50497. this._onchange = new Array();
  50498. /**
  50499. * The value of the path cursor
  50500. */
  50501. this.value = 0;
  50502. /**
  50503. * The animation array of the path cursor
  50504. */
  50505. this.animations = new Array();
  50506. }
  50507. /**
  50508. * Gets the cursor point on the path
  50509. * @returns A point on the path cursor at the cursor location
  50510. */
  50511. PathCursor.prototype.getPoint = function () {
  50512. var point = this.path.getPointAtLengthPosition(this.value);
  50513. return new BABYLON.Vector3(point.x, 0, point.y);
  50514. };
  50515. /**
  50516. * Moves the cursor ahead by the step amount
  50517. * @param step The amount to move the cursor forward
  50518. * @returns This path cursor
  50519. */
  50520. PathCursor.prototype.moveAhead = function (step) {
  50521. if (step === void 0) { step = 0.002; }
  50522. this.move(step);
  50523. return this;
  50524. };
  50525. /**
  50526. * Moves the cursor behind by the step amount
  50527. * @param step The amount to move the cursor back
  50528. * @returns This path cursor
  50529. */
  50530. PathCursor.prototype.moveBack = function (step) {
  50531. if (step === void 0) { step = 0.002; }
  50532. this.move(-step);
  50533. return this;
  50534. };
  50535. /**
  50536. * Moves the cursor by the step amount
  50537. * If the step amount is greater than one, an exception is thrown
  50538. * @param step The amount to move the cursor
  50539. * @returns This path cursor
  50540. */
  50541. PathCursor.prototype.move = function (step) {
  50542. if (Math.abs(step) > 1) {
  50543. throw "step size should be less than 1.";
  50544. }
  50545. this.value += step;
  50546. this.ensureLimits();
  50547. this.raiseOnChange();
  50548. return this;
  50549. };
  50550. /**
  50551. * Ensures that the value is limited between zero and one
  50552. * @returns This path cursor
  50553. */
  50554. PathCursor.prototype.ensureLimits = function () {
  50555. while (this.value > 1) {
  50556. this.value -= 1;
  50557. }
  50558. while (this.value < 0) {
  50559. this.value += 1;
  50560. }
  50561. return this;
  50562. };
  50563. /**
  50564. * Runs onchange callbacks on change (used by the animation engine)
  50565. * @returns This path cursor
  50566. */
  50567. PathCursor.prototype.raiseOnChange = function () {
  50568. var _this = this;
  50569. this._onchange.forEach(function (f) { return f(_this); });
  50570. return this;
  50571. };
  50572. /**
  50573. * Executes a function on change
  50574. * @param f A path cursor onchange callback
  50575. * @returns This path cursor
  50576. */
  50577. PathCursor.prototype.onchange = function (f) {
  50578. this._onchange.push(f);
  50579. return this;
  50580. };
  50581. return PathCursor;
  50582. }());
  50583. BABYLON.PathCursor = PathCursor;
  50584. /**
  50585. * Enum for the animation key frame interpolation type
  50586. */
  50587. var AnimationKeyInterpolation;
  50588. (function (AnimationKeyInterpolation) {
  50589. /**
  50590. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50591. */
  50592. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50593. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50594. /**
  50595. * Class used to store any kind of animation
  50596. */
  50597. var Animation = /** @class */ (function () {
  50598. /**
  50599. * Initializes the animation
  50600. * @param name Name of the animation
  50601. * @param targetProperty Property to animate
  50602. * @param framePerSecond The frames per second of the animation
  50603. * @param dataType The data type of the animation
  50604. * @param loopMode The loop mode of the animation
  50605. * @param enableBlendings Specifies if blending should be enabled
  50606. */
  50607. function Animation(
  50608. /**Name of the animation */
  50609. name,
  50610. /**Property to animate */
  50611. targetProperty,
  50612. /**The frames per second of the animation */
  50613. framePerSecond,
  50614. /**The data type of the animation */
  50615. dataType,
  50616. /**The loop mode of the animation */
  50617. loopMode,
  50618. /**Specifies if blending should be enabled */
  50619. enableBlending) {
  50620. this.name = name;
  50621. this.targetProperty = targetProperty;
  50622. this.framePerSecond = framePerSecond;
  50623. this.dataType = dataType;
  50624. this.loopMode = loopMode;
  50625. this.enableBlending = enableBlending;
  50626. /**
  50627. * @hidden Internal use only
  50628. */
  50629. this._runtimeAnimations = new Array();
  50630. /**
  50631. * The set of event that will be linked to this animation
  50632. */
  50633. this._events = new Array();
  50634. /**
  50635. * Stores the blending speed of the animation
  50636. */
  50637. this.blendingSpeed = 0.01;
  50638. /**
  50639. * Stores the animation ranges for the animation
  50640. */
  50641. this._ranges = {};
  50642. this.targetPropertyPath = targetProperty.split(".");
  50643. this.dataType = dataType;
  50644. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50645. }
  50646. /**
  50647. * @hidden Internal use
  50648. */
  50649. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50650. var dataType = undefined;
  50651. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50652. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50653. }
  50654. else if (from instanceof BABYLON.Quaternion) {
  50655. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50656. }
  50657. else if (from instanceof BABYLON.Vector3) {
  50658. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50659. }
  50660. else if (from instanceof BABYLON.Vector2) {
  50661. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50662. }
  50663. else if (from instanceof BABYLON.Color3) {
  50664. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50665. }
  50666. else if (from instanceof BABYLON.Size) {
  50667. dataType = Animation.ANIMATIONTYPE_SIZE;
  50668. }
  50669. if (dataType == undefined) {
  50670. return null;
  50671. }
  50672. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50673. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50674. animation.setKeys(keys);
  50675. if (easingFunction !== undefined) {
  50676. animation.setEasingFunction(easingFunction);
  50677. }
  50678. return animation;
  50679. };
  50680. /**
  50681. * Sets up an animation
  50682. * @param property The property to animate
  50683. * @param animationType The animation type to apply
  50684. * @param framePerSecond The frames per second of the animation
  50685. * @param easingFunction The easing function used in the animation
  50686. * @returns The created animation
  50687. */
  50688. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50689. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50690. animation.setEasingFunction(easingFunction);
  50691. return animation;
  50692. };
  50693. /**
  50694. * Create and start an animation on a node
  50695. * @param name defines the name of the global animation that will be run on all nodes
  50696. * @param node defines the root node where the animation will take place
  50697. * @param targetProperty defines property to animate
  50698. * @param framePerSecond defines the number of frame per second yo use
  50699. * @param totalFrame defines the number of frames in total
  50700. * @param from defines the initial value
  50701. * @param to defines the final value
  50702. * @param loopMode defines which loop mode you want to use (off by default)
  50703. * @param easingFunction defines the easing function to use (linear by default)
  50704. * @param onAnimationEnd defines the callback to call when animation end
  50705. * @returns the animatable created for this animation
  50706. */
  50707. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50708. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50709. if (!animation) {
  50710. return null;
  50711. }
  50712. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50713. };
  50714. /**
  50715. * Create and start an animation on a node and its descendants
  50716. * @param name defines the name of the global animation that will be run on all nodes
  50717. * @param node defines the root node where the animation will take place
  50718. * @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
  50719. * @param targetProperty defines property to animate
  50720. * @param framePerSecond defines the number of frame per second to use
  50721. * @param totalFrame defines the number of frames in total
  50722. * @param from defines the initial value
  50723. * @param to defines the final value
  50724. * @param loopMode defines which loop mode you want to use (off by default)
  50725. * @param easingFunction defines the easing function to use (linear by default)
  50726. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50727. * @returns the list of animatables created for all nodes
  50728. * @example https://www.babylonjs-playground.com/#MH0VLI
  50729. */
  50730. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50731. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50732. if (!animation) {
  50733. return null;
  50734. }
  50735. var scene = node.getScene();
  50736. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50737. };
  50738. /**
  50739. * Creates a new animation, merges it with the existing animations and starts it
  50740. * @param name Name of the animation
  50741. * @param node Node which contains the scene that begins the animations
  50742. * @param targetProperty Specifies which property to animate
  50743. * @param framePerSecond The frames per second of the animation
  50744. * @param totalFrame The total number of frames
  50745. * @param from The frame at the beginning of the animation
  50746. * @param to The frame at the end of the animation
  50747. * @param loopMode Specifies the loop mode of the animation
  50748. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50749. * @param onAnimationEnd Callback to run once the animation is complete
  50750. * @returns Nullable animation
  50751. */
  50752. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50753. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50754. if (!animation) {
  50755. return null;
  50756. }
  50757. node.animations.push(animation);
  50758. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50759. };
  50760. /**
  50761. * Transition property of an host to the target Value
  50762. * @param property The property to transition
  50763. * @param targetValue The target Value of the property
  50764. * @param host The object where the property to animate belongs
  50765. * @param scene Scene used to run the animation
  50766. * @param frameRate Framerate (in frame/s) to use
  50767. * @param transition The transition type we want to use
  50768. * @param duration The duration of the animation, in milliseconds
  50769. * @param onAnimationEnd Callback trigger at the end of the animation
  50770. * @returns Nullable animation
  50771. */
  50772. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50773. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50774. if (duration <= 0) {
  50775. host[property] = targetValue;
  50776. if (onAnimationEnd) {
  50777. onAnimationEnd();
  50778. }
  50779. return null;
  50780. }
  50781. var endFrame = frameRate * (duration / 1000);
  50782. transition.setKeys([{
  50783. frame: 0,
  50784. value: host[property].clone ? host[property].clone() : host[property]
  50785. },
  50786. {
  50787. frame: endFrame,
  50788. value: targetValue
  50789. }]);
  50790. if (!host.animations) {
  50791. host.animations = [];
  50792. }
  50793. host.animations.push(transition);
  50794. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50795. animation.onAnimationEnd = onAnimationEnd;
  50796. return animation;
  50797. };
  50798. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50799. /**
  50800. * Return the array of runtime animations currently using this animation
  50801. */
  50802. get: function () {
  50803. return this._runtimeAnimations;
  50804. },
  50805. enumerable: true,
  50806. configurable: true
  50807. });
  50808. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50809. /**
  50810. * Specifies if any of the runtime animations are currently running
  50811. */
  50812. get: function () {
  50813. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50814. var runtimeAnimation = _a[_i];
  50815. if (!runtimeAnimation.isStopped) {
  50816. return true;
  50817. }
  50818. }
  50819. return false;
  50820. },
  50821. enumerable: true,
  50822. configurable: true
  50823. });
  50824. // Methods
  50825. /**
  50826. * Converts the animation to a string
  50827. * @param fullDetails support for multiple levels of logging within scene loading
  50828. * @returns String form of the animation
  50829. */
  50830. Animation.prototype.toString = function (fullDetails) {
  50831. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50832. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50833. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50834. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50835. if (fullDetails) {
  50836. ret += ", Ranges: {";
  50837. var first = true;
  50838. for (var name in this._ranges) {
  50839. if (first) {
  50840. ret += ", ";
  50841. first = false;
  50842. }
  50843. ret += name;
  50844. }
  50845. ret += "}";
  50846. }
  50847. return ret;
  50848. };
  50849. /**
  50850. * Add an event to this animation
  50851. * @param event Event to add
  50852. */
  50853. Animation.prototype.addEvent = function (event) {
  50854. this._events.push(event);
  50855. };
  50856. /**
  50857. * Remove all events found at the given frame
  50858. * @param frame The frame to remove events from
  50859. */
  50860. Animation.prototype.removeEvents = function (frame) {
  50861. for (var index = 0; index < this._events.length; index++) {
  50862. if (this._events[index].frame === frame) {
  50863. this._events.splice(index, 1);
  50864. index--;
  50865. }
  50866. }
  50867. };
  50868. /**
  50869. * Retrieves all the events from the animation
  50870. * @returns Events from the animation
  50871. */
  50872. Animation.prototype.getEvents = function () {
  50873. return this._events;
  50874. };
  50875. /**
  50876. * Creates an animation range
  50877. * @param name Name of the animation range
  50878. * @param from Starting frame of the animation range
  50879. * @param to Ending frame of the animation
  50880. */
  50881. Animation.prototype.createRange = function (name, from, to) {
  50882. // check name not already in use; could happen for bones after serialized
  50883. if (!this._ranges[name]) {
  50884. this._ranges[name] = new AnimationRange(name, from, to);
  50885. }
  50886. };
  50887. /**
  50888. * Deletes an animation range by name
  50889. * @param name Name of the animation range to delete
  50890. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50891. */
  50892. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50893. if (deleteFrames === void 0) { deleteFrames = true; }
  50894. var range = this._ranges[name];
  50895. if (!range) {
  50896. return;
  50897. }
  50898. if (deleteFrames) {
  50899. var from = range.from;
  50900. var to = range.to;
  50901. // this loop MUST go high to low for multiple splices to work
  50902. for (var key = this._keys.length - 1; key >= 0; key--) {
  50903. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50904. this._keys.splice(key, 1);
  50905. }
  50906. }
  50907. }
  50908. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50909. };
  50910. /**
  50911. * Gets the animation range by name, or null if not defined
  50912. * @param name Name of the animation range
  50913. * @returns Nullable animation range
  50914. */
  50915. Animation.prototype.getRange = function (name) {
  50916. return this._ranges[name];
  50917. };
  50918. /**
  50919. * Gets the key frames from the animation
  50920. * @returns The key frames of the animation
  50921. */
  50922. Animation.prototype.getKeys = function () {
  50923. return this._keys;
  50924. };
  50925. /**
  50926. * Gets the highest frame rate of the animation
  50927. * @returns Highest frame rate of the animation
  50928. */
  50929. Animation.prototype.getHighestFrame = function () {
  50930. var ret = 0;
  50931. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50932. if (ret < this._keys[key].frame) {
  50933. ret = this._keys[key].frame;
  50934. }
  50935. }
  50936. return ret;
  50937. };
  50938. /**
  50939. * Gets the easing function of the animation
  50940. * @returns Easing function of the animation
  50941. */
  50942. Animation.prototype.getEasingFunction = function () {
  50943. return this._easingFunction;
  50944. };
  50945. /**
  50946. * Sets the easing function of the animation
  50947. * @param easingFunction A custom mathematical formula for animation
  50948. */
  50949. Animation.prototype.setEasingFunction = function (easingFunction) {
  50950. this._easingFunction = easingFunction;
  50951. };
  50952. /**
  50953. * Interpolates a scalar linearly
  50954. * @param startValue Start value of the animation curve
  50955. * @param endValue End value of the animation curve
  50956. * @param gradient Scalar amount to interpolate
  50957. * @returns Interpolated scalar value
  50958. */
  50959. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50960. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50961. };
  50962. /**
  50963. * Interpolates a scalar cubically
  50964. * @param startValue Start value of the animation curve
  50965. * @param outTangent End tangent of the animation
  50966. * @param endValue End value of the animation curve
  50967. * @param inTangent Start tangent of the animation curve
  50968. * @param gradient Scalar amount to interpolate
  50969. * @returns Interpolated scalar value
  50970. */
  50971. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50972. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50973. };
  50974. /**
  50975. * Interpolates a quaternion using a spherical linear interpolation
  50976. * @param startValue Start value of the animation curve
  50977. * @param endValue End value of the animation curve
  50978. * @param gradient Scalar amount to interpolate
  50979. * @returns Interpolated quaternion value
  50980. */
  50981. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50982. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50983. };
  50984. /**
  50985. * Interpolates a quaternion cubically
  50986. * @param startValue Start value of the animation curve
  50987. * @param outTangent End tangent of the animation curve
  50988. * @param endValue End value of the animation curve
  50989. * @param inTangent Start tangent of the animation curve
  50990. * @param gradient Scalar amount to interpolate
  50991. * @returns Interpolated quaternion value
  50992. */
  50993. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50994. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50995. };
  50996. /**
  50997. * Interpolates a Vector3 linearl
  50998. * @param startValue Start value of the animation curve
  50999. * @param endValue End value of the animation curve
  51000. * @param gradient Scalar amount to interpolate
  51001. * @returns Interpolated scalar value
  51002. */
  51003. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51004. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51005. };
  51006. /**
  51007. * Interpolates a Vector3 cubically
  51008. * @param startValue Start value of the animation curve
  51009. * @param outTangent End tangent of the animation
  51010. * @param endValue End value of the animation curve
  51011. * @param inTangent Start tangent of the animation curve
  51012. * @param gradient Scalar amount to interpolate
  51013. * @returns InterpolatedVector3 value
  51014. */
  51015. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51016. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51017. };
  51018. /**
  51019. * Interpolates a Vector2 linearly
  51020. * @param startValue Start value of the animation curve
  51021. * @param endValue End value of the animation curve
  51022. * @param gradient Scalar amount to interpolate
  51023. * @returns Interpolated Vector2 value
  51024. */
  51025. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51026. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51027. };
  51028. /**
  51029. * Interpolates a Vector2 cubically
  51030. * @param startValue Start value of the animation curve
  51031. * @param outTangent End tangent of the animation
  51032. * @param endValue End value of the animation curve
  51033. * @param inTangent Start tangent of the animation curve
  51034. * @param gradient Scalar amount to interpolate
  51035. * @returns Interpolated Vector2 value
  51036. */
  51037. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51038. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51039. };
  51040. /**
  51041. * Interpolates a size linearly
  51042. * @param startValue Start value of the animation curve
  51043. * @param endValue End value of the animation curve
  51044. * @param gradient Scalar amount to interpolate
  51045. * @returns Interpolated Size value
  51046. */
  51047. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51048. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51049. };
  51050. /**
  51051. * Interpolates a Color3 linearly
  51052. * @param startValue Start value of the animation curve
  51053. * @param endValue End value of the animation curve
  51054. * @param gradient Scalar amount to interpolate
  51055. * @returns Interpolated Color3 value
  51056. */
  51057. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51058. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51059. };
  51060. /**
  51061. * @hidden Internal use only
  51062. */
  51063. Animation.prototype._getKeyValue = function (value) {
  51064. if (typeof value === "function") {
  51065. return value();
  51066. }
  51067. return value;
  51068. };
  51069. /**
  51070. * @hidden Internal use only
  51071. */
  51072. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51073. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51074. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51075. }
  51076. var keys = this.getKeys();
  51077. // Try to get a hash to find the right key
  51078. 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));
  51079. if (keys[startKeyIndex].frame >= currentFrame) {
  51080. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51081. startKeyIndex--;
  51082. }
  51083. }
  51084. for (var key = startKeyIndex; key < keys.length; key++) {
  51085. var endKey = keys[key + 1];
  51086. if (endKey.frame >= currentFrame) {
  51087. var startKey = keys[key];
  51088. var startValue = this._getKeyValue(startKey.value);
  51089. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51090. return startValue;
  51091. }
  51092. var endValue = this._getKeyValue(endKey.value);
  51093. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51094. var frameDelta = endKey.frame - startKey.frame;
  51095. // gradient : percent of currentFrame between the frame inf and the frame sup
  51096. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51097. // check for easingFunction and correction of gradient
  51098. var easingFunction = this.getEasingFunction();
  51099. if (easingFunction != null) {
  51100. gradient = easingFunction.ease(gradient);
  51101. }
  51102. switch (this.dataType) {
  51103. // Float
  51104. case Animation.ANIMATIONTYPE_FLOAT:
  51105. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51106. switch (loopMode) {
  51107. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51108. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51109. return floatValue;
  51110. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51111. return offsetValue * repeatCount + floatValue;
  51112. }
  51113. break;
  51114. // Quaternion
  51115. case Animation.ANIMATIONTYPE_QUATERNION:
  51116. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51117. switch (loopMode) {
  51118. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51119. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51120. return quatValue;
  51121. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51122. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51123. }
  51124. return quatValue;
  51125. // Vector3
  51126. case Animation.ANIMATIONTYPE_VECTOR3:
  51127. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51128. switch (loopMode) {
  51129. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51130. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51131. return vec3Value;
  51132. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51133. return vec3Value.add(offsetValue.scale(repeatCount));
  51134. }
  51135. // Vector2
  51136. case Animation.ANIMATIONTYPE_VECTOR2:
  51137. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51138. switch (loopMode) {
  51139. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51140. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51141. return vec2Value;
  51142. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51143. return vec2Value.add(offsetValue.scale(repeatCount));
  51144. }
  51145. // Size
  51146. case Animation.ANIMATIONTYPE_SIZE:
  51147. switch (loopMode) {
  51148. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51149. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51150. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51151. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51152. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51153. }
  51154. // Color3
  51155. case Animation.ANIMATIONTYPE_COLOR3:
  51156. switch (loopMode) {
  51157. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51158. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51159. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51160. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51161. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51162. }
  51163. // Matrix
  51164. case Animation.ANIMATIONTYPE_MATRIX:
  51165. switch (loopMode) {
  51166. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51167. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51168. if (Animation.AllowMatricesInterpolation) {
  51169. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51170. }
  51171. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51172. return startValue;
  51173. }
  51174. default:
  51175. break;
  51176. }
  51177. break;
  51178. }
  51179. }
  51180. return this._getKeyValue(keys[keys.length - 1].value);
  51181. };
  51182. /**
  51183. * Defines the function to use to interpolate matrices
  51184. * @param startValue defines the start matrix
  51185. * @param endValue defines the end matrix
  51186. * @param gradient defines the gradient between both matrices
  51187. * @param result defines an optional target matrix where to store the interpolation
  51188. * @returns the interpolated matrix
  51189. */
  51190. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51191. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51192. if (result) {
  51193. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51194. return result;
  51195. }
  51196. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51197. }
  51198. if (result) {
  51199. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51200. return result;
  51201. }
  51202. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51203. };
  51204. /**
  51205. * Makes a copy of the animation
  51206. * @returns Cloned animation
  51207. */
  51208. Animation.prototype.clone = function () {
  51209. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51210. clone.enableBlending = this.enableBlending;
  51211. clone.blendingSpeed = this.blendingSpeed;
  51212. if (this._keys) {
  51213. clone.setKeys(this._keys);
  51214. }
  51215. if (this._ranges) {
  51216. clone._ranges = {};
  51217. for (var name in this._ranges) {
  51218. var range = this._ranges[name];
  51219. if (!range) {
  51220. continue;
  51221. }
  51222. clone._ranges[name] = range.clone();
  51223. }
  51224. }
  51225. return clone;
  51226. };
  51227. /**
  51228. * Sets the key frames of the animation
  51229. * @param values The animation key frames to set
  51230. */
  51231. Animation.prototype.setKeys = function (values) {
  51232. this._keys = values.slice(0);
  51233. };
  51234. /**
  51235. * Serializes the animation to an object
  51236. * @returns Serialized object
  51237. */
  51238. Animation.prototype.serialize = function () {
  51239. var serializationObject = {};
  51240. serializationObject.name = this.name;
  51241. serializationObject.property = this.targetProperty;
  51242. serializationObject.framePerSecond = this.framePerSecond;
  51243. serializationObject.dataType = this.dataType;
  51244. serializationObject.loopBehavior = this.loopMode;
  51245. serializationObject.enableBlending = this.enableBlending;
  51246. serializationObject.blendingSpeed = this.blendingSpeed;
  51247. var dataType = this.dataType;
  51248. serializationObject.keys = [];
  51249. var keys = this.getKeys();
  51250. for (var index = 0; index < keys.length; index++) {
  51251. var animationKey = keys[index];
  51252. var key = {};
  51253. key.frame = animationKey.frame;
  51254. switch (dataType) {
  51255. case Animation.ANIMATIONTYPE_FLOAT:
  51256. key.values = [animationKey.value];
  51257. break;
  51258. case Animation.ANIMATIONTYPE_QUATERNION:
  51259. case Animation.ANIMATIONTYPE_MATRIX:
  51260. case Animation.ANIMATIONTYPE_VECTOR3:
  51261. case Animation.ANIMATIONTYPE_COLOR3:
  51262. key.values = animationKey.value.asArray();
  51263. break;
  51264. }
  51265. serializationObject.keys.push(key);
  51266. }
  51267. serializationObject.ranges = [];
  51268. for (var name in this._ranges) {
  51269. var source = this._ranges[name];
  51270. if (!source) {
  51271. continue;
  51272. }
  51273. var range = {};
  51274. range.name = name;
  51275. range.from = source.from;
  51276. range.to = source.to;
  51277. serializationObject.ranges.push(range);
  51278. }
  51279. return serializationObject;
  51280. };
  51281. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51282. /**
  51283. * Get the float animation type
  51284. */
  51285. get: function () {
  51286. return Animation._ANIMATIONTYPE_FLOAT;
  51287. },
  51288. enumerable: true,
  51289. configurable: true
  51290. });
  51291. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51292. /**
  51293. * Get the Vector3 animation type
  51294. */
  51295. get: function () {
  51296. return Animation._ANIMATIONTYPE_VECTOR3;
  51297. },
  51298. enumerable: true,
  51299. configurable: true
  51300. });
  51301. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51302. /**
  51303. * Get the Vectpr2 animation type
  51304. */
  51305. get: function () {
  51306. return Animation._ANIMATIONTYPE_VECTOR2;
  51307. },
  51308. enumerable: true,
  51309. configurable: true
  51310. });
  51311. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51312. /**
  51313. * Get the Size animation type
  51314. */
  51315. get: function () {
  51316. return Animation._ANIMATIONTYPE_SIZE;
  51317. },
  51318. enumerable: true,
  51319. configurable: true
  51320. });
  51321. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51322. /**
  51323. * Get the Quaternion animation type
  51324. */
  51325. get: function () {
  51326. return Animation._ANIMATIONTYPE_QUATERNION;
  51327. },
  51328. enumerable: true,
  51329. configurable: true
  51330. });
  51331. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51332. /**
  51333. * Get the Matrix animation type
  51334. */
  51335. get: function () {
  51336. return Animation._ANIMATIONTYPE_MATRIX;
  51337. },
  51338. enumerable: true,
  51339. configurable: true
  51340. });
  51341. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51342. /**
  51343. * Get the Color3 animation type
  51344. */
  51345. get: function () {
  51346. return Animation._ANIMATIONTYPE_COLOR3;
  51347. },
  51348. enumerable: true,
  51349. configurable: true
  51350. });
  51351. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51352. /**
  51353. * Get the Relative Loop Mode
  51354. */
  51355. get: function () {
  51356. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51357. },
  51358. enumerable: true,
  51359. configurable: true
  51360. });
  51361. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51362. /**
  51363. * Get the Cycle Loop Mode
  51364. */
  51365. get: function () {
  51366. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51367. },
  51368. enumerable: true,
  51369. configurable: true
  51370. });
  51371. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51372. /**
  51373. * Get the Constant Loop Mode
  51374. */
  51375. get: function () {
  51376. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51377. },
  51378. enumerable: true,
  51379. configurable: true
  51380. });
  51381. /** @hidden */
  51382. Animation._UniversalLerp = function (left, right, amount) {
  51383. var constructor = left.constructor;
  51384. if (constructor.Lerp) { // Lerp supported
  51385. return constructor.Lerp(left, right, amount);
  51386. }
  51387. else if (constructor.Slerp) { // Slerp supported
  51388. return constructor.Slerp(left, right, amount);
  51389. }
  51390. else if (left.toFixed) { // Number
  51391. return left * (1.0 - amount) + amount * right;
  51392. }
  51393. else { // Blending not supported
  51394. return right;
  51395. }
  51396. };
  51397. /**
  51398. * Parses an animation object and creates an animation
  51399. * @param parsedAnimation Parsed animation object
  51400. * @returns Animation object
  51401. */
  51402. Animation.Parse = function (parsedAnimation) {
  51403. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51404. var dataType = parsedAnimation.dataType;
  51405. var keys = [];
  51406. var data;
  51407. var index;
  51408. if (parsedAnimation.enableBlending) {
  51409. animation.enableBlending = parsedAnimation.enableBlending;
  51410. }
  51411. if (parsedAnimation.blendingSpeed) {
  51412. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51413. }
  51414. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51415. var key = parsedAnimation.keys[index];
  51416. var inTangent;
  51417. var outTangent;
  51418. switch (dataType) {
  51419. case Animation.ANIMATIONTYPE_FLOAT:
  51420. data = key.values[0];
  51421. if (key.values.length >= 1) {
  51422. inTangent = key.values[1];
  51423. }
  51424. if (key.values.length >= 2) {
  51425. outTangent = key.values[2];
  51426. }
  51427. break;
  51428. case Animation.ANIMATIONTYPE_QUATERNION:
  51429. data = BABYLON.Quaternion.FromArray(key.values);
  51430. if (key.values.length >= 8) {
  51431. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51432. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51433. inTangent = _inTangent;
  51434. }
  51435. }
  51436. if (key.values.length >= 12) {
  51437. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51438. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51439. outTangent = _outTangent;
  51440. }
  51441. }
  51442. break;
  51443. case Animation.ANIMATIONTYPE_MATRIX:
  51444. data = BABYLON.Matrix.FromArray(key.values);
  51445. break;
  51446. case Animation.ANIMATIONTYPE_COLOR3:
  51447. data = BABYLON.Color3.FromArray(key.values);
  51448. break;
  51449. case Animation.ANIMATIONTYPE_VECTOR3:
  51450. default:
  51451. data = BABYLON.Vector3.FromArray(key.values);
  51452. break;
  51453. }
  51454. var keyData = {};
  51455. keyData.frame = key.frame;
  51456. keyData.value = data;
  51457. if (inTangent != undefined) {
  51458. keyData.inTangent = inTangent;
  51459. }
  51460. if (outTangent != undefined) {
  51461. keyData.outTangent = outTangent;
  51462. }
  51463. keys.push(keyData);
  51464. }
  51465. animation.setKeys(keys);
  51466. if (parsedAnimation.ranges) {
  51467. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51468. data = parsedAnimation.ranges[index];
  51469. animation.createRange(data.name, data.from, data.to);
  51470. }
  51471. }
  51472. return animation;
  51473. };
  51474. /**
  51475. * Appends the serialized animations from the source animations
  51476. * @param source Source containing the animations
  51477. * @param destination Target to store the animations
  51478. */
  51479. Animation.AppendSerializedAnimations = function (source, destination) {
  51480. if (source.animations) {
  51481. destination.animations = [];
  51482. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51483. var animation = source.animations[animationIndex];
  51484. destination.animations.push(animation.serialize());
  51485. }
  51486. }
  51487. };
  51488. /**
  51489. * Use matrix interpolation instead of using direct key value when animating matrices
  51490. */
  51491. Animation.AllowMatricesInterpolation = false;
  51492. /**
  51493. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51494. */
  51495. Animation.AllowMatrixDecomposeForInterpolation = true;
  51496. // Statics
  51497. /**
  51498. * Float animation type
  51499. */
  51500. Animation._ANIMATIONTYPE_FLOAT = 0;
  51501. /**
  51502. * Vector3 animation type
  51503. */
  51504. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51505. /**
  51506. * Quaternion animation type
  51507. */
  51508. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51509. /**
  51510. * Matrix animation type
  51511. */
  51512. Animation._ANIMATIONTYPE_MATRIX = 3;
  51513. /**
  51514. * Color3 animation type
  51515. */
  51516. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51517. /**
  51518. * Vector2 animation type
  51519. */
  51520. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51521. /**
  51522. * Size animation type
  51523. */
  51524. Animation._ANIMATIONTYPE_SIZE = 6;
  51525. /**
  51526. * Relative Loop Mode
  51527. */
  51528. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51529. /**
  51530. * Cycle Loop Mode
  51531. */
  51532. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51533. /**
  51534. * Constant Loop Mode
  51535. */
  51536. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51537. return Animation;
  51538. }());
  51539. BABYLON.Animation = Animation;
  51540. })(BABYLON || (BABYLON = {}));
  51541. //# sourceMappingURL=babylon.animation.js.map
  51542. var BABYLON;
  51543. (function (BABYLON) {
  51544. /**
  51545. * This class defines the direct association between an animation and a target
  51546. */
  51547. var TargetedAnimation = /** @class */ (function () {
  51548. function TargetedAnimation() {
  51549. }
  51550. return TargetedAnimation;
  51551. }());
  51552. BABYLON.TargetedAnimation = TargetedAnimation;
  51553. /**
  51554. * Use this class to create coordinated animations on multiple targets
  51555. */
  51556. var AnimationGroup = /** @class */ (function () {
  51557. function AnimationGroup(name, scene) {
  51558. if (scene === void 0) { scene = null; }
  51559. this.name = name;
  51560. this._targetedAnimations = new Array();
  51561. this._animatables = new Array();
  51562. this._from = Number.MAX_VALUE;
  51563. this._to = -Number.MAX_VALUE;
  51564. this._speedRatio = 1;
  51565. this.onAnimationEndObservable = new BABYLON.Observable();
  51566. /**
  51567. * This observable will notify when all animations have ended.
  51568. */
  51569. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51570. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51571. this._scene.animationGroups.push(this);
  51572. }
  51573. Object.defineProperty(AnimationGroup.prototype, "from", {
  51574. /**
  51575. * Gets the first frame
  51576. */
  51577. get: function () {
  51578. return this._from;
  51579. },
  51580. enumerable: true,
  51581. configurable: true
  51582. });
  51583. Object.defineProperty(AnimationGroup.prototype, "to", {
  51584. /**
  51585. * Gets the last frame
  51586. */
  51587. get: function () {
  51588. return this._to;
  51589. },
  51590. enumerable: true,
  51591. configurable: true
  51592. });
  51593. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51594. /**
  51595. * Define if the animations are started
  51596. */
  51597. get: function () {
  51598. return this._isStarted;
  51599. },
  51600. enumerable: true,
  51601. configurable: true
  51602. });
  51603. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51604. /**
  51605. * Gets or sets the speed ratio to use for all animations
  51606. */
  51607. get: function () {
  51608. return this._speedRatio;
  51609. },
  51610. /**
  51611. * Gets or sets the speed ratio to use for all animations
  51612. */
  51613. set: function (value) {
  51614. if (this._speedRatio === value) {
  51615. return;
  51616. }
  51617. this._speedRatio = value;
  51618. for (var index = 0; index < this._animatables.length; index++) {
  51619. var animatable = this._animatables[index];
  51620. animatable.speedRatio = this._speedRatio;
  51621. }
  51622. },
  51623. enumerable: true,
  51624. configurable: true
  51625. });
  51626. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51627. /**
  51628. * Gets the targeted animations for this animation group
  51629. */
  51630. get: function () {
  51631. return this._targetedAnimations;
  51632. },
  51633. enumerable: true,
  51634. configurable: true
  51635. });
  51636. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51637. /**
  51638. * returning the list of animatables controlled by this animation group.
  51639. */
  51640. get: function () {
  51641. return this._animatables;
  51642. },
  51643. enumerable: true,
  51644. configurable: true
  51645. });
  51646. /**
  51647. * Add an animation (with its target) in the group
  51648. * @param animation defines the animation we want to add
  51649. * @param target defines the target of the animation
  51650. * @returns the {BABYLON.TargetedAnimation} object
  51651. */
  51652. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51653. var targetedAnimation = {
  51654. animation: animation,
  51655. target: target
  51656. };
  51657. var keys = animation.getKeys();
  51658. if (this._from > keys[0].frame) {
  51659. this._from = keys[0].frame;
  51660. }
  51661. if (this._to < keys[keys.length - 1].frame) {
  51662. this._to = keys[keys.length - 1].frame;
  51663. }
  51664. this._targetedAnimations.push(targetedAnimation);
  51665. return targetedAnimation;
  51666. };
  51667. /**
  51668. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51669. * It can add constant keys at begin or end
  51670. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51671. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51672. */
  51673. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51674. if (beginFrame === void 0) { beginFrame = null; }
  51675. if (endFrame === void 0) { endFrame = null; }
  51676. if (beginFrame == null)
  51677. beginFrame = this._from;
  51678. if (endFrame == null)
  51679. endFrame = this._to;
  51680. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51681. var targetedAnimation = this._targetedAnimations[index];
  51682. var keys = targetedAnimation.animation.getKeys();
  51683. var startKey = keys[0];
  51684. var endKey = keys[keys.length - 1];
  51685. if (startKey.frame > beginFrame) {
  51686. var newKey = {
  51687. frame: beginFrame,
  51688. value: startKey.value,
  51689. inTangent: startKey.inTangent,
  51690. outTangent: startKey.outTangent,
  51691. interpolation: startKey.interpolation
  51692. };
  51693. keys.splice(0, 0, newKey);
  51694. }
  51695. if (endKey.frame < endFrame) {
  51696. var newKey = {
  51697. frame: endFrame,
  51698. value: endKey.value,
  51699. inTangent: endKey.outTangent,
  51700. outTangent: endKey.outTangent,
  51701. interpolation: endKey.interpolation
  51702. };
  51703. keys.push(newKey);
  51704. }
  51705. }
  51706. this._from = beginFrame;
  51707. this._to = endFrame;
  51708. return this;
  51709. };
  51710. /**
  51711. * Start all animations on given targets
  51712. * @param loop defines if animations must loop
  51713. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51714. * @param from defines the from key (optional)
  51715. * @param to defines the to key (optional)
  51716. * @returns the current animation group
  51717. */
  51718. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51719. var _this = this;
  51720. if (loop === void 0) { loop = false; }
  51721. if (speedRatio === void 0) { speedRatio = 1; }
  51722. if (this._isStarted || this._targetedAnimations.length === 0) {
  51723. return this;
  51724. }
  51725. var _loop_1 = function (targetedAnimation) {
  51726. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51727. animatable.onAnimationEnd = function () {
  51728. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51729. _this._checkAnimationGroupEnded(animatable);
  51730. };
  51731. this_1._animatables.push(animatable);
  51732. };
  51733. var this_1 = this;
  51734. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51735. var targetedAnimation = _a[_i];
  51736. _loop_1(targetedAnimation);
  51737. }
  51738. this._speedRatio = speedRatio;
  51739. this._isStarted = true;
  51740. return this;
  51741. };
  51742. /**
  51743. * Pause all animations
  51744. */
  51745. AnimationGroup.prototype.pause = function () {
  51746. if (!this._isStarted) {
  51747. return this;
  51748. }
  51749. for (var index = 0; index < this._animatables.length; index++) {
  51750. var animatable = this._animatables[index];
  51751. animatable.pause();
  51752. }
  51753. return this;
  51754. };
  51755. /**
  51756. * Play all animations to initial state
  51757. * This function will start() the animations if they were not started or will restart() them if they were paused
  51758. * @param loop defines if animations must loop
  51759. */
  51760. AnimationGroup.prototype.play = function (loop) {
  51761. // only if all animatables are ready and exist
  51762. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51763. if (loop !== undefined) {
  51764. for (var index = 0; index < this._animatables.length; index++) {
  51765. var animatable = this._animatables[index];
  51766. animatable.loopAnimation = loop;
  51767. }
  51768. }
  51769. this.restart();
  51770. }
  51771. else {
  51772. this.stop();
  51773. this.start(loop, this._speedRatio);
  51774. }
  51775. return this;
  51776. };
  51777. /**
  51778. * Reset all animations to initial state
  51779. */
  51780. AnimationGroup.prototype.reset = function () {
  51781. if (!this._isStarted) {
  51782. return this;
  51783. }
  51784. for (var index = 0; index < this._animatables.length; index++) {
  51785. var animatable = this._animatables[index];
  51786. animatable.reset();
  51787. }
  51788. return this;
  51789. };
  51790. /**
  51791. * Restart animations from key 0
  51792. */
  51793. AnimationGroup.prototype.restart = function () {
  51794. if (!this._isStarted) {
  51795. return this;
  51796. }
  51797. for (var index = 0; index < this._animatables.length; index++) {
  51798. var animatable = this._animatables[index];
  51799. animatable.restart();
  51800. }
  51801. return this;
  51802. };
  51803. /**
  51804. * Stop all animations
  51805. */
  51806. AnimationGroup.prototype.stop = function () {
  51807. if (!this._isStarted) {
  51808. return this;
  51809. }
  51810. for (var index = 0; index < this._animatables.length; index++) {
  51811. var animatable = this._animatables[index];
  51812. animatable.stop();
  51813. }
  51814. this._isStarted = false;
  51815. return this;
  51816. };
  51817. /**
  51818. * Set animation weight for all animatables
  51819. * @param weight defines the weight to use
  51820. * @return the animationGroup
  51821. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51822. */
  51823. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51824. for (var index = 0; index < this._animatables.length; index++) {
  51825. var animatable = this._animatables[index];
  51826. animatable.weight = weight;
  51827. }
  51828. return this;
  51829. };
  51830. /**
  51831. * Synchronize and normalize all animatables with a source animatable
  51832. * @param root defines the root animatable to synchronize with
  51833. * @return the animationGroup
  51834. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51835. */
  51836. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51837. for (var index = 0; index < this._animatables.length; index++) {
  51838. var animatable = this._animatables[index];
  51839. animatable.syncWith(root);
  51840. }
  51841. return this;
  51842. };
  51843. /**
  51844. * Goes to a specific frame in this animation group
  51845. * @param frame the frame number to go to
  51846. * @return the animationGroup
  51847. */
  51848. AnimationGroup.prototype.goToFrame = function (frame) {
  51849. if (!this._isStarted) {
  51850. return this;
  51851. }
  51852. for (var index = 0; index < this._animatables.length; index++) {
  51853. var animatable = this._animatables[index];
  51854. animatable.goToFrame(frame);
  51855. }
  51856. return this;
  51857. };
  51858. /**
  51859. * Dispose all associated resources
  51860. */
  51861. AnimationGroup.prototype.dispose = function () {
  51862. this._targetedAnimations = [];
  51863. this._animatables = [];
  51864. var index = this._scene.animationGroups.indexOf(this);
  51865. if (index > -1) {
  51866. this._scene.animationGroups.splice(index, 1);
  51867. }
  51868. };
  51869. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51870. // animatable should be taken out of the array
  51871. var idx = this._animatables.indexOf(animatable);
  51872. if (idx > -1) {
  51873. this._animatables.splice(idx, 1);
  51874. }
  51875. // all animatables were removed? animation group ended!
  51876. if (this._animatables.length === 0) {
  51877. this._isStarted = false;
  51878. this.onAnimationGroupEndObservable.notifyObservers(this);
  51879. }
  51880. };
  51881. return AnimationGroup;
  51882. }());
  51883. BABYLON.AnimationGroup = AnimationGroup;
  51884. })(BABYLON || (BABYLON = {}));
  51885. //# sourceMappingURL=babylon.animationGroup.js.map
  51886. var BABYLON;
  51887. (function (BABYLON) {
  51888. /**
  51889. * Defines a runtime animation
  51890. */
  51891. var RuntimeAnimation = /** @class */ (function () {
  51892. /**
  51893. * Create a new RuntimeAnimation object
  51894. * @param target defines the target of the animation
  51895. * @param animation defines the source animation object
  51896. * @param scene defines the hosting scene
  51897. * @param host defines the initiating Animatable
  51898. */
  51899. function RuntimeAnimation(target, animation, scene, host) {
  51900. var _this = this;
  51901. this._events = new Array();
  51902. /**
  51903. * The current frame of the runtime animation
  51904. */
  51905. this._currentFrame = 0;
  51906. /**
  51907. * The original value of the runtime animation
  51908. */
  51909. this._originalValue = new Array();
  51910. /**
  51911. * The offsets cache of the runtime animation
  51912. */
  51913. this._offsetsCache = {};
  51914. /**
  51915. * The high limits cache of the runtime animation
  51916. */
  51917. this._highLimitsCache = {};
  51918. /**
  51919. * Specifies if the runtime animation has been stopped
  51920. */
  51921. this._stopped = false;
  51922. /**
  51923. * The blending factor of the runtime animation
  51924. */
  51925. this._blendingFactor = 0;
  51926. /**
  51927. * The target path of the runtime animation
  51928. */
  51929. this._targetPath = "";
  51930. /**
  51931. * The weight of the runtime animation
  51932. */
  51933. this._weight = 1.0;
  51934. /**
  51935. * The ratio offset of the runtime animation
  51936. */
  51937. this._ratioOffset = 0;
  51938. /**
  51939. * The previous delay of the runtime animation
  51940. */
  51941. this._previousDelay = 0;
  51942. /**
  51943. * The previous ratio of the runtime animation
  51944. */
  51945. this._previousRatio = 0;
  51946. this._animation = animation;
  51947. this._target = target;
  51948. this._scene = scene;
  51949. this._host = host;
  51950. animation._runtimeAnimations.push(this);
  51951. // Cloning events locally
  51952. var events = animation.getEvents();
  51953. if (events && events.length > 0) {
  51954. events.forEach(function (e) {
  51955. _this._events.push(e._clone());
  51956. });
  51957. }
  51958. }
  51959. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51960. /**
  51961. * Gets the current frame of the runtime animation
  51962. */
  51963. get: function () {
  51964. return this._currentFrame;
  51965. },
  51966. enumerable: true,
  51967. configurable: true
  51968. });
  51969. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51970. /**
  51971. * Gets the weight of the runtime animation
  51972. */
  51973. get: function () {
  51974. return this._weight;
  51975. },
  51976. enumerable: true,
  51977. configurable: true
  51978. });
  51979. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51980. /**
  51981. * Gets the current value of the runtime animation
  51982. */
  51983. get: function () {
  51984. return this._currentValue;
  51985. },
  51986. enumerable: true,
  51987. configurable: true
  51988. });
  51989. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51990. /**
  51991. * Gets the target path of the runtime animation
  51992. */
  51993. get: function () {
  51994. return this._targetPath;
  51995. },
  51996. enumerable: true,
  51997. configurable: true
  51998. });
  51999. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52000. /**
  52001. * Gets the actual target of the runtime animation
  52002. */
  52003. get: function () {
  52004. return this._activeTarget;
  52005. },
  52006. enumerable: true,
  52007. configurable: true
  52008. });
  52009. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52010. /**
  52011. * Gets the animation from the runtime animation
  52012. */
  52013. get: function () {
  52014. return this._animation;
  52015. },
  52016. enumerable: true,
  52017. configurable: true
  52018. });
  52019. /**
  52020. * Resets the runtime animation to the beginning
  52021. * @param restoreOriginal defines whether to restore the target property to the original value
  52022. */
  52023. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52024. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52025. if (restoreOriginal) {
  52026. if (this._target instanceof Array) {
  52027. var index = 0;
  52028. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52029. var target = _a[_i];
  52030. if (this._originalValue[index] !== undefined) {
  52031. this._setValue(target, this._originalValue[index], -1);
  52032. }
  52033. index++;
  52034. }
  52035. }
  52036. else {
  52037. if (this._originalValue[0] !== undefined) {
  52038. this._setValue(this._target, this._originalValue[0], -1);
  52039. }
  52040. }
  52041. }
  52042. this._offsetsCache = {};
  52043. this._highLimitsCache = {};
  52044. this._currentFrame = 0;
  52045. this._blendingFactor = 0;
  52046. this._originalValue = new Array();
  52047. // Events
  52048. for (var index = 0; index < this._events.length; index++) {
  52049. this._events[index].isDone = false;
  52050. }
  52051. };
  52052. /**
  52053. * Specifies if the runtime animation is stopped
  52054. * @returns Boolean specifying if the runtime animation is stopped
  52055. */
  52056. RuntimeAnimation.prototype.isStopped = function () {
  52057. return this._stopped;
  52058. };
  52059. /**
  52060. * Disposes of the runtime animation
  52061. */
  52062. RuntimeAnimation.prototype.dispose = function () {
  52063. var index = this._animation.runtimeAnimations.indexOf(this);
  52064. if (index > -1) {
  52065. this._animation.runtimeAnimations.splice(index, 1);
  52066. }
  52067. };
  52068. /**
  52069. * Interpolates the animation from the current frame
  52070. * @param currentFrame The frame to interpolate the animation to
  52071. * @param repeatCount The number of times that the animation should loop
  52072. * @param loopMode The type of looping mode to use
  52073. * @param offsetValue Animation offset value
  52074. * @param highLimitValue The high limit value
  52075. * @returns The interpolated value
  52076. */
  52077. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52078. this._currentFrame = currentFrame;
  52079. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52080. this._workValue = BABYLON.Matrix.Zero();
  52081. }
  52082. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52083. };
  52084. /**
  52085. * Apply the interpolated value to the target
  52086. * @param currentValue defines the value computed by the animation
  52087. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52088. */
  52089. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52090. if (weight === void 0) { weight = 1.0; }
  52091. if (this._target instanceof Array) {
  52092. var index = 0;
  52093. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52094. var target = _a[_i];
  52095. this._setValue(target, currentValue, weight, index);
  52096. index++;
  52097. }
  52098. }
  52099. else {
  52100. this._setValue(this._target, currentValue, weight);
  52101. }
  52102. };
  52103. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52104. if (targetIndex === void 0) { targetIndex = 0; }
  52105. // Set value
  52106. var path;
  52107. var destination;
  52108. var targetPropertyPath = this._animation.targetPropertyPath;
  52109. if (targetPropertyPath.length > 1) {
  52110. var property = target[targetPropertyPath[0]];
  52111. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52112. property = property[targetPropertyPath[index]];
  52113. }
  52114. path = targetPropertyPath[targetPropertyPath.length - 1];
  52115. destination = property;
  52116. }
  52117. else {
  52118. path = targetPropertyPath[0];
  52119. destination = target;
  52120. }
  52121. this._targetPath = path;
  52122. this._activeTarget = destination;
  52123. this._weight = weight;
  52124. if (this._originalValue[targetIndex] === undefined) {
  52125. var originalValue = void 0;
  52126. if (destination.getRestPose && path === "_matrix") { // For bones
  52127. originalValue = destination.getRestPose();
  52128. }
  52129. else {
  52130. originalValue = destination[path];
  52131. }
  52132. if (originalValue && originalValue.clone) {
  52133. this._originalValue[targetIndex] = originalValue.clone();
  52134. }
  52135. else {
  52136. this._originalValue[targetIndex] = originalValue;
  52137. }
  52138. }
  52139. // Blending
  52140. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52141. if (enableBlending && this._blendingFactor <= 1.0) {
  52142. if (!this._originalBlendValue) {
  52143. var originalValue = destination[path];
  52144. if (originalValue.clone) {
  52145. this._originalBlendValue = originalValue.clone();
  52146. }
  52147. else {
  52148. this._originalBlendValue = originalValue;
  52149. }
  52150. }
  52151. if (this._originalBlendValue.m) { // Matrix
  52152. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52153. if (this._currentValue) {
  52154. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52155. }
  52156. else {
  52157. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52158. }
  52159. }
  52160. else {
  52161. if (this._currentValue) {
  52162. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52163. }
  52164. else {
  52165. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52166. }
  52167. }
  52168. }
  52169. else {
  52170. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52171. }
  52172. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52173. this._blendingFactor += blendingSpeed;
  52174. }
  52175. else {
  52176. this._currentValue = currentValue;
  52177. }
  52178. if (weight !== -1.0) {
  52179. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52180. }
  52181. else {
  52182. destination[path] = this._currentValue;
  52183. }
  52184. if (target.markAsDirty) {
  52185. target.markAsDirty(this._animation.targetProperty);
  52186. }
  52187. };
  52188. /**
  52189. * Gets the loop pmode of the runtime animation
  52190. * @returns Loop Mode
  52191. */
  52192. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52193. if (this._target && this._target.animationPropertiesOverride) {
  52194. return this._target.animationPropertiesOverride.loopMode;
  52195. }
  52196. return this._animation.loopMode;
  52197. };
  52198. /**
  52199. * Move the current animation to a given frame
  52200. * @param frame defines the frame to move to
  52201. */
  52202. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52203. var keys = this._animation.getKeys();
  52204. if (frame < keys[0].frame) {
  52205. frame = keys[0].frame;
  52206. }
  52207. else if (frame > keys[keys.length - 1].frame) {
  52208. frame = keys[keys.length - 1].frame;
  52209. }
  52210. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52211. this.setValue(currentValue, -1);
  52212. };
  52213. /**
  52214. * @hidden Internal use only
  52215. */
  52216. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52217. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52218. this._ratioOffset = this._previousRatio - newRatio;
  52219. };
  52220. /**
  52221. * Execute the current animation
  52222. * @param delay defines the delay to add to the current frame
  52223. * @param from defines the lower bound of the animation range
  52224. * @param to defines the upper bound of the animation range
  52225. * @param loop defines if the current animation must loop
  52226. * @param speedRatio defines the current speed ratio
  52227. * @param weight defines the weight of the animation (default is -1 so no weight)
  52228. * @returns a boolean indicating if the animation has ended
  52229. */
  52230. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52231. if (weight === void 0) { weight = -1.0; }
  52232. var targetPropertyPath = this._animation.targetPropertyPath;
  52233. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52234. this._stopped = true;
  52235. return false;
  52236. }
  52237. var returnValue = true;
  52238. var keys = this._animation.getKeys();
  52239. // Adding a start key at frame 0 if missing
  52240. if (keys[0].frame !== 0) {
  52241. var newKey = { frame: 0, value: keys[0].value };
  52242. keys.splice(0, 0, newKey);
  52243. }
  52244. // Check limits
  52245. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52246. from = keys[0].frame;
  52247. }
  52248. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52249. to = keys[keys.length - 1].frame;
  52250. }
  52251. //to and from cannot be the same key
  52252. if (from === to) {
  52253. if (from > keys[0].frame) {
  52254. from--;
  52255. }
  52256. else if (to < keys[keys.length - 1].frame) {
  52257. to++;
  52258. }
  52259. }
  52260. // Compute ratio
  52261. var range = to - from;
  52262. var offsetValue;
  52263. // ratio represents the frame delta between from and to
  52264. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52265. var highLimitValue = 0;
  52266. this._previousDelay = delay;
  52267. this._previousRatio = ratio;
  52268. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52269. returnValue = false;
  52270. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52271. }
  52272. else {
  52273. // Get max value if required
  52274. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52275. var keyOffset = to.toString() + from.toString();
  52276. if (!this._offsetsCache[keyOffset]) {
  52277. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52278. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52279. switch (this._animation.dataType) {
  52280. // Float
  52281. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52282. this._offsetsCache[keyOffset] = toValue - fromValue;
  52283. break;
  52284. // Quaternion
  52285. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52286. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52287. break;
  52288. // Vector3
  52289. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52290. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52291. // Vector2
  52292. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52293. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52294. // Size
  52295. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52296. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52297. // Color3
  52298. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52299. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52300. default:
  52301. break;
  52302. }
  52303. this._highLimitsCache[keyOffset] = toValue;
  52304. }
  52305. highLimitValue = this._highLimitsCache[keyOffset];
  52306. offsetValue = this._offsetsCache[keyOffset];
  52307. }
  52308. }
  52309. if (offsetValue === undefined) {
  52310. switch (this._animation.dataType) {
  52311. // Float
  52312. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52313. offsetValue = 0;
  52314. break;
  52315. // Quaternion
  52316. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52317. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52318. break;
  52319. // Vector3
  52320. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52321. offsetValue = BABYLON.Vector3.Zero();
  52322. break;
  52323. // Vector2
  52324. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52325. offsetValue = BABYLON.Vector2.Zero();
  52326. break;
  52327. // Size
  52328. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52329. offsetValue = BABYLON.Size.Zero();
  52330. break;
  52331. // Color3
  52332. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52333. offsetValue = BABYLON.Color3.Black();
  52334. }
  52335. }
  52336. // Compute value
  52337. var repeatCount = (ratio / range) >> 0;
  52338. var currentFrame = returnValue ? from + ratio % range : to;
  52339. // Need to normalize?
  52340. if (this._host && this._host.syncRoot) {
  52341. var syncRoot = this._host.syncRoot;
  52342. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52343. currentFrame = from + (to - from) * hostNormalizedFrame;
  52344. }
  52345. // Reset events if looping
  52346. var events = this._events;
  52347. if (range > 0 && this.currentFrame > currentFrame ||
  52348. range < 0 && this.currentFrame < currentFrame) {
  52349. // Need to reset animation events
  52350. for (var index = 0; index < events.length; index++) {
  52351. if (!events[index].onlyOnce) {
  52352. // reset event, the animation is looping
  52353. events[index].isDone = false;
  52354. }
  52355. }
  52356. }
  52357. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52358. // Set value
  52359. this.setValue(currentValue, weight);
  52360. // Check events
  52361. for (var index = 0; index < events.length; index++) {
  52362. // Make sure current frame has passed event frame and that event frame is within the current range
  52363. // Also, handle both forward and reverse animations
  52364. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52365. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52366. var event = events[index];
  52367. if (!event.isDone) {
  52368. // If event should be done only once, remove it.
  52369. if (event.onlyOnce) {
  52370. events.splice(index, 1);
  52371. index--;
  52372. }
  52373. event.isDone = true;
  52374. event.action();
  52375. } // Don't do anything if the event has already be done.
  52376. }
  52377. }
  52378. if (!returnValue) {
  52379. this._stopped = true;
  52380. }
  52381. return returnValue;
  52382. };
  52383. return RuntimeAnimation;
  52384. }());
  52385. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52386. })(BABYLON || (BABYLON = {}));
  52387. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52388. var BABYLON;
  52389. (function (BABYLON) {
  52390. var Animatable = /** @class */ (function () {
  52391. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52392. if (fromFrame === void 0) { fromFrame = 0; }
  52393. if (toFrame === void 0) { toFrame = 100; }
  52394. if (loopAnimation === void 0) { loopAnimation = false; }
  52395. if (speedRatio === void 0) { speedRatio = 1.0; }
  52396. this.target = target;
  52397. this.fromFrame = fromFrame;
  52398. this.toFrame = toFrame;
  52399. this.loopAnimation = loopAnimation;
  52400. this.onAnimationEnd = onAnimationEnd;
  52401. this._localDelayOffset = null;
  52402. this._pausedDelay = null;
  52403. this._runtimeAnimations = new Array();
  52404. this._paused = false;
  52405. this._speedRatio = 1;
  52406. this._weight = -1.0;
  52407. this.animationStarted = false;
  52408. /**
  52409. * Observer raised when the animation ends
  52410. */
  52411. this.onAnimationEndObservable = new BABYLON.Observable();
  52412. this._scene = scene;
  52413. if (animations) {
  52414. this.appendAnimations(target, animations);
  52415. }
  52416. this._speedRatio = speedRatio;
  52417. scene._activeAnimatables.push(this);
  52418. }
  52419. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52420. /**
  52421. * Gets the root Animatable used to synchronize and normalize animations
  52422. */
  52423. get: function () {
  52424. return this._syncRoot;
  52425. },
  52426. enumerable: true,
  52427. configurable: true
  52428. });
  52429. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52430. /**
  52431. * Gets the current frame of the first RuntimeAnimation
  52432. * Used to synchronize Animatables
  52433. */
  52434. get: function () {
  52435. if (this._runtimeAnimations.length === 0) {
  52436. return 0;
  52437. }
  52438. return this._runtimeAnimations[0].currentFrame;
  52439. },
  52440. enumerable: true,
  52441. configurable: true
  52442. });
  52443. Object.defineProperty(Animatable.prototype, "weight", {
  52444. /**
  52445. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52446. */
  52447. get: function () {
  52448. return this._weight;
  52449. },
  52450. set: function (value) {
  52451. if (value === -1) { // -1 is ok and means no weight
  52452. this._weight = -1;
  52453. return;
  52454. }
  52455. // Else weight must be in [0, 1] range
  52456. this._weight = Math.min(Math.max(value, 0), 1.0);
  52457. },
  52458. enumerable: true,
  52459. configurable: true
  52460. });
  52461. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52462. /**
  52463. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52464. */
  52465. get: function () {
  52466. return this._speedRatio;
  52467. },
  52468. set: function (value) {
  52469. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52470. var animation = this._runtimeAnimations[index];
  52471. animation._prepareForSpeedRatioChange(value);
  52472. }
  52473. this._speedRatio = value;
  52474. },
  52475. enumerable: true,
  52476. configurable: true
  52477. });
  52478. // Methods
  52479. /**
  52480. * Synchronize and normalize current Animatable with a source Animatable
  52481. * This is useful when using animation weights and when animations are not of the same length
  52482. * @param root defines the root Animatable to synchronize with
  52483. * @returns the current Animatable
  52484. */
  52485. Animatable.prototype.syncWith = function (root) {
  52486. this._syncRoot = root;
  52487. if (root) {
  52488. // Make sure this animatable will animate after the root
  52489. var index = this._scene._activeAnimatables.indexOf(this);
  52490. if (index > -1) {
  52491. this._scene._activeAnimatables.splice(index, 1);
  52492. this._scene._activeAnimatables.push(this);
  52493. }
  52494. }
  52495. return this;
  52496. };
  52497. Animatable.prototype.getAnimations = function () {
  52498. return this._runtimeAnimations;
  52499. };
  52500. Animatable.prototype.appendAnimations = function (target, animations) {
  52501. for (var index = 0; index < animations.length; index++) {
  52502. var animation = animations[index];
  52503. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52504. }
  52505. };
  52506. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52507. var runtimeAnimations = this._runtimeAnimations;
  52508. for (var index = 0; index < runtimeAnimations.length; index++) {
  52509. if (runtimeAnimations[index].animation.targetProperty === property) {
  52510. return runtimeAnimations[index].animation;
  52511. }
  52512. }
  52513. return null;
  52514. };
  52515. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52516. var runtimeAnimations = this._runtimeAnimations;
  52517. for (var index = 0; index < runtimeAnimations.length; index++) {
  52518. if (runtimeAnimations[index].animation.targetProperty === property) {
  52519. return runtimeAnimations[index];
  52520. }
  52521. }
  52522. return null;
  52523. };
  52524. Animatable.prototype.reset = function () {
  52525. var runtimeAnimations = this._runtimeAnimations;
  52526. for (var index = 0; index < runtimeAnimations.length; index++) {
  52527. runtimeAnimations[index].reset(true);
  52528. }
  52529. this._localDelayOffset = null;
  52530. this._pausedDelay = null;
  52531. };
  52532. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52533. var runtimeAnimations = this._runtimeAnimations;
  52534. for (var index = 0; index < runtimeAnimations.length; index++) {
  52535. runtimeAnimations[index].animation.enableBlending = true;
  52536. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52537. }
  52538. };
  52539. Animatable.prototype.disableBlending = function () {
  52540. var runtimeAnimations = this._runtimeAnimations;
  52541. for (var index = 0; index < runtimeAnimations.length; index++) {
  52542. runtimeAnimations[index].animation.enableBlending = false;
  52543. }
  52544. };
  52545. Animatable.prototype.goToFrame = function (frame) {
  52546. var runtimeAnimations = this._runtimeAnimations;
  52547. if (runtimeAnimations[0]) {
  52548. var fps = runtimeAnimations[0].animation.framePerSecond;
  52549. var currentFrame = runtimeAnimations[0].currentFrame;
  52550. var adjustTime = frame - currentFrame;
  52551. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52552. if (this._localDelayOffset === null) {
  52553. this._localDelayOffset = 0;
  52554. }
  52555. this._localDelayOffset -= delay;
  52556. }
  52557. for (var index = 0; index < runtimeAnimations.length; index++) {
  52558. runtimeAnimations[index].goToFrame(frame);
  52559. }
  52560. };
  52561. Animatable.prototype.pause = function () {
  52562. if (this._paused) {
  52563. return;
  52564. }
  52565. this._paused = true;
  52566. };
  52567. Animatable.prototype.restart = function () {
  52568. this._paused = false;
  52569. };
  52570. Animatable.prototype._raiseOnAnimationEnd = function () {
  52571. if (this.onAnimationEnd) {
  52572. this.onAnimationEnd();
  52573. }
  52574. this.onAnimationEndObservable.notifyObservers(this);
  52575. };
  52576. Animatable.prototype.stop = function (animationName) {
  52577. if (animationName) {
  52578. var idx = this._scene._activeAnimatables.indexOf(this);
  52579. if (idx > -1) {
  52580. var runtimeAnimations = this._runtimeAnimations;
  52581. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52582. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52583. continue;
  52584. }
  52585. runtimeAnimations[index].dispose();
  52586. runtimeAnimations.splice(index, 1);
  52587. }
  52588. if (runtimeAnimations.length == 0) {
  52589. this._scene._activeAnimatables.splice(idx, 1);
  52590. this._raiseOnAnimationEnd();
  52591. }
  52592. }
  52593. }
  52594. else {
  52595. var index = this._scene._activeAnimatables.indexOf(this);
  52596. if (index > -1) {
  52597. this._scene._activeAnimatables.splice(index, 1);
  52598. var runtimeAnimations = this._runtimeAnimations;
  52599. for (var index = 0; index < runtimeAnimations.length; index++) {
  52600. runtimeAnimations[index].dispose();
  52601. }
  52602. this._raiseOnAnimationEnd();
  52603. }
  52604. }
  52605. };
  52606. /**
  52607. * Wait asynchronously for the animation to end
  52608. * @returns a promise which will be fullfilled when the animation ends
  52609. */
  52610. Animatable.prototype.waitAsync = function () {
  52611. var _this = this;
  52612. return new Promise(function (resolve, reject) {
  52613. _this.onAnimationEndObservable.add(function () {
  52614. resolve(_this);
  52615. }, undefined, undefined, _this, true);
  52616. });
  52617. };
  52618. /** @hidden */
  52619. Animatable.prototype._animate = function (delay) {
  52620. if (this._paused) {
  52621. this.animationStarted = false;
  52622. if (this._pausedDelay === null) {
  52623. this._pausedDelay = delay;
  52624. }
  52625. return true;
  52626. }
  52627. if (this._localDelayOffset === null) {
  52628. this._localDelayOffset = delay;
  52629. this._pausedDelay = null;
  52630. }
  52631. else if (this._pausedDelay !== null) {
  52632. this._localDelayOffset += delay - this._pausedDelay;
  52633. this._pausedDelay = null;
  52634. }
  52635. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52636. return true;
  52637. }
  52638. // Animating
  52639. var running = false;
  52640. var runtimeAnimations = this._runtimeAnimations;
  52641. var index;
  52642. for (index = 0; index < runtimeAnimations.length; index++) {
  52643. var animation = runtimeAnimations[index];
  52644. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52645. running = running || isRunning;
  52646. }
  52647. this.animationStarted = running;
  52648. if (!running) {
  52649. // Remove from active animatables
  52650. index = this._scene._activeAnimatables.indexOf(this);
  52651. this._scene._activeAnimatables.splice(index, 1);
  52652. // Dispose all runtime animations
  52653. for (index = 0; index < runtimeAnimations.length; index++) {
  52654. runtimeAnimations[index].dispose();
  52655. }
  52656. this._raiseOnAnimationEnd();
  52657. this.onAnimationEnd = null;
  52658. this.onAnimationEndObservable.clear();
  52659. }
  52660. return running;
  52661. };
  52662. return Animatable;
  52663. }());
  52664. BABYLON.Animatable = Animatable;
  52665. })(BABYLON || (BABYLON = {}));
  52666. //# sourceMappingURL=babylon.animatable.js.map
  52667. var BABYLON;
  52668. (function (BABYLON) {
  52669. var EasingFunction = /** @class */ (function () {
  52670. function EasingFunction() {
  52671. // Properties
  52672. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52673. }
  52674. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52675. get: function () {
  52676. return EasingFunction._EASINGMODE_EASEIN;
  52677. },
  52678. enumerable: true,
  52679. configurable: true
  52680. });
  52681. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52682. get: function () {
  52683. return EasingFunction._EASINGMODE_EASEOUT;
  52684. },
  52685. enumerable: true,
  52686. configurable: true
  52687. });
  52688. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52689. get: function () {
  52690. return EasingFunction._EASINGMODE_EASEINOUT;
  52691. },
  52692. enumerable: true,
  52693. configurable: true
  52694. });
  52695. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52696. var n = Math.min(Math.max(easingMode, 0), 2);
  52697. this._easingMode = n;
  52698. };
  52699. EasingFunction.prototype.getEasingMode = function () {
  52700. return this._easingMode;
  52701. };
  52702. EasingFunction.prototype.easeInCore = function (gradient) {
  52703. throw new Error('You must implement this method');
  52704. };
  52705. EasingFunction.prototype.ease = function (gradient) {
  52706. switch (this._easingMode) {
  52707. case EasingFunction.EASINGMODE_EASEIN:
  52708. return this.easeInCore(gradient);
  52709. case EasingFunction.EASINGMODE_EASEOUT:
  52710. return (1 - this.easeInCore(1 - gradient));
  52711. }
  52712. if (gradient >= 0.5) {
  52713. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52714. }
  52715. return (this.easeInCore(gradient * 2) * 0.5);
  52716. };
  52717. //Statics
  52718. EasingFunction._EASINGMODE_EASEIN = 0;
  52719. EasingFunction._EASINGMODE_EASEOUT = 1;
  52720. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52721. return EasingFunction;
  52722. }());
  52723. BABYLON.EasingFunction = EasingFunction;
  52724. var CircleEase = /** @class */ (function (_super) {
  52725. __extends(CircleEase, _super);
  52726. function CircleEase() {
  52727. return _super !== null && _super.apply(this, arguments) || this;
  52728. }
  52729. CircleEase.prototype.easeInCore = function (gradient) {
  52730. gradient = Math.max(0, Math.min(1, gradient));
  52731. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52732. };
  52733. return CircleEase;
  52734. }(EasingFunction));
  52735. BABYLON.CircleEase = CircleEase;
  52736. var BackEase = /** @class */ (function (_super) {
  52737. __extends(BackEase, _super);
  52738. function BackEase(amplitude) {
  52739. if (amplitude === void 0) { amplitude = 1; }
  52740. var _this = _super.call(this) || this;
  52741. _this.amplitude = amplitude;
  52742. return _this;
  52743. }
  52744. BackEase.prototype.easeInCore = function (gradient) {
  52745. var num = Math.max(0, this.amplitude);
  52746. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52747. };
  52748. return BackEase;
  52749. }(EasingFunction));
  52750. BABYLON.BackEase = BackEase;
  52751. var BounceEase = /** @class */ (function (_super) {
  52752. __extends(BounceEase, _super);
  52753. function BounceEase(bounces, bounciness) {
  52754. if (bounces === void 0) { bounces = 3; }
  52755. if (bounciness === void 0) { bounciness = 2; }
  52756. var _this = _super.call(this) || this;
  52757. _this.bounces = bounces;
  52758. _this.bounciness = bounciness;
  52759. return _this;
  52760. }
  52761. BounceEase.prototype.easeInCore = function (gradient) {
  52762. var y = Math.max(0.0, this.bounces);
  52763. var bounciness = this.bounciness;
  52764. if (bounciness <= 1.0) {
  52765. bounciness = 1.001;
  52766. }
  52767. var num9 = Math.pow(bounciness, y);
  52768. var num5 = 1.0 - bounciness;
  52769. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52770. var num15 = gradient * num4;
  52771. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52772. var num3 = Math.floor(num65);
  52773. var num13 = num3 + 1.0;
  52774. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52775. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52776. var num7 = (num8 + num12) * 0.5;
  52777. var num6 = gradient - num7;
  52778. var num2 = num7 - num8;
  52779. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52780. };
  52781. return BounceEase;
  52782. }(EasingFunction));
  52783. BABYLON.BounceEase = BounceEase;
  52784. var CubicEase = /** @class */ (function (_super) {
  52785. __extends(CubicEase, _super);
  52786. function CubicEase() {
  52787. return _super !== null && _super.apply(this, arguments) || this;
  52788. }
  52789. CubicEase.prototype.easeInCore = function (gradient) {
  52790. return (gradient * gradient * gradient);
  52791. };
  52792. return CubicEase;
  52793. }(EasingFunction));
  52794. BABYLON.CubicEase = CubicEase;
  52795. var ElasticEase = /** @class */ (function (_super) {
  52796. __extends(ElasticEase, _super);
  52797. function ElasticEase(oscillations, springiness) {
  52798. if (oscillations === void 0) { oscillations = 3; }
  52799. if (springiness === void 0) { springiness = 3; }
  52800. var _this = _super.call(this) || this;
  52801. _this.oscillations = oscillations;
  52802. _this.springiness = springiness;
  52803. return _this;
  52804. }
  52805. ElasticEase.prototype.easeInCore = function (gradient) {
  52806. var num2;
  52807. var num3 = Math.max(0.0, this.oscillations);
  52808. var num = Math.max(0.0, this.springiness);
  52809. if (num == 0) {
  52810. num2 = gradient;
  52811. }
  52812. else {
  52813. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52814. }
  52815. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52816. };
  52817. return ElasticEase;
  52818. }(EasingFunction));
  52819. BABYLON.ElasticEase = ElasticEase;
  52820. var ExponentialEase = /** @class */ (function (_super) {
  52821. __extends(ExponentialEase, _super);
  52822. function ExponentialEase(exponent) {
  52823. if (exponent === void 0) { exponent = 2; }
  52824. var _this = _super.call(this) || this;
  52825. _this.exponent = exponent;
  52826. return _this;
  52827. }
  52828. ExponentialEase.prototype.easeInCore = function (gradient) {
  52829. if (this.exponent <= 0) {
  52830. return gradient;
  52831. }
  52832. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52833. };
  52834. return ExponentialEase;
  52835. }(EasingFunction));
  52836. BABYLON.ExponentialEase = ExponentialEase;
  52837. var PowerEase = /** @class */ (function (_super) {
  52838. __extends(PowerEase, _super);
  52839. function PowerEase(power) {
  52840. if (power === void 0) { power = 2; }
  52841. var _this = _super.call(this) || this;
  52842. _this.power = power;
  52843. return _this;
  52844. }
  52845. PowerEase.prototype.easeInCore = function (gradient) {
  52846. var y = Math.max(0.0, this.power);
  52847. return Math.pow(gradient, y);
  52848. };
  52849. return PowerEase;
  52850. }(EasingFunction));
  52851. BABYLON.PowerEase = PowerEase;
  52852. var QuadraticEase = /** @class */ (function (_super) {
  52853. __extends(QuadraticEase, _super);
  52854. function QuadraticEase() {
  52855. return _super !== null && _super.apply(this, arguments) || this;
  52856. }
  52857. QuadraticEase.prototype.easeInCore = function (gradient) {
  52858. return (gradient * gradient);
  52859. };
  52860. return QuadraticEase;
  52861. }(EasingFunction));
  52862. BABYLON.QuadraticEase = QuadraticEase;
  52863. var QuarticEase = /** @class */ (function (_super) {
  52864. __extends(QuarticEase, _super);
  52865. function QuarticEase() {
  52866. return _super !== null && _super.apply(this, arguments) || this;
  52867. }
  52868. QuarticEase.prototype.easeInCore = function (gradient) {
  52869. return (gradient * gradient * gradient * gradient);
  52870. };
  52871. return QuarticEase;
  52872. }(EasingFunction));
  52873. BABYLON.QuarticEase = QuarticEase;
  52874. var QuinticEase = /** @class */ (function (_super) {
  52875. __extends(QuinticEase, _super);
  52876. function QuinticEase() {
  52877. return _super !== null && _super.apply(this, arguments) || this;
  52878. }
  52879. QuinticEase.prototype.easeInCore = function (gradient) {
  52880. return (gradient * gradient * gradient * gradient * gradient);
  52881. };
  52882. return QuinticEase;
  52883. }(EasingFunction));
  52884. BABYLON.QuinticEase = QuinticEase;
  52885. var SineEase = /** @class */ (function (_super) {
  52886. __extends(SineEase, _super);
  52887. function SineEase() {
  52888. return _super !== null && _super.apply(this, arguments) || this;
  52889. }
  52890. SineEase.prototype.easeInCore = function (gradient) {
  52891. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52892. };
  52893. return SineEase;
  52894. }(EasingFunction));
  52895. BABYLON.SineEase = SineEase;
  52896. var BezierCurveEase = /** @class */ (function (_super) {
  52897. __extends(BezierCurveEase, _super);
  52898. function BezierCurveEase(x1, y1, x2, y2) {
  52899. if (x1 === void 0) { x1 = 0; }
  52900. if (y1 === void 0) { y1 = 0; }
  52901. if (x2 === void 0) { x2 = 1; }
  52902. if (y2 === void 0) { y2 = 1; }
  52903. var _this = _super.call(this) || this;
  52904. _this.x1 = x1;
  52905. _this.y1 = y1;
  52906. _this.x2 = x2;
  52907. _this.y2 = y2;
  52908. return _this;
  52909. }
  52910. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52911. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52912. };
  52913. return BezierCurveEase;
  52914. }(EasingFunction));
  52915. BABYLON.BezierCurveEase = BezierCurveEase;
  52916. })(BABYLON || (BABYLON = {}));
  52917. //# sourceMappingURL=babylon.easing.js.map
  52918. var BABYLON;
  52919. (function (BABYLON) {
  52920. /**
  52921. * A Condition applied to an Action
  52922. */
  52923. var Condition = /** @class */ (function () {
  52924. /**
  52925. * Creates a new Condition
  52926. * @param actionManager the manager of the action the condition is applied to
  52927. */
  52928. function Condition(actionManager) {
  52929. this._actionManager = actionManager;
  52930. }
  52931. /**
  52932. * Check if the current condition is valid
  52933. * @returns a boolean
  52934. */
  52935. Condition.prototype.isValid = function () {
  52936. return true;
  52937. };
  52938. /**
  52939. * Internal only
  52940. * @hidden
  52941. */
  52942. Condition.prototype._getProperty = function (propertyPath) {
  52943. return this._actionManager._getProperty(propertyPath);
  52944. };
  52945. /**
  52946. * Internal only
  52947. * @hidden
  52948. */
  52949. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52950. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52951. };
  52952. /**
  52953. * Serialize placeholder for child classes
  52954. * @returns the serialized object
  52955. */
  52956. Condition.prototype.serialize = function () {
  52957. };
  52958. /**
  52959. * Internal only
  52960. * @hidden
  52961. */
  52962. Condition.prototype._serialize = function (serializedCondition) {
  52963. return {
  52964. type: 2,
  52965. children: [],
  52966. name: serializedCondition.name,
  52967. properties: serializedCondition.properties
  52968. };
  52969. };
  52970. return Condition;
  52971. }());
  52972. BABYLON.Condition = Condition;
  52973. /**
  52974. * Defines specific conditional operators as extensions of Condition
  52975. */
  52976. var ValueCondition = /** @class */ (function (_super) {
  52977. __extends(ValueCondition, _super);
  52978. /**
  52979. * Creates a new ValueCondition
  52980. * @param actionManager manager for the action the condition applies to
  52981. * @param target for the action
  52982. * @param propertyPath path to specify the property of the target the conditional operator uses
  52983. * @param value the value compared by the conditional operator against the current value of the property
  52984. * @param operator the conditional operator, default ValueCondition.IsEqual
  52985. */
  52986. function ValueCondition(actionManager, target,
  52987. /** path to specify the property of the target the conditional operator uses */
  52988. propertyPath,
  52989. /** the value compared by the conditional operator against the current value of the property */
  52990. value,
  52991. /** the conditional operator, default ValueCondition.IsEqual */
  52992. operator) {
  52993. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52994. var _this = _super.call(this, actionManager) || this;
  52995. _this.propertyPath = propertyPath;
  52996. _this.value = value;
  52997. _this.operator = operator;
  52998. _this._target = target;
  52999. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53000. _this._property = _this._getProperty(_this.propertyPath);
  53001. return _this;
  53002. }
  53003. Object.defineProperty(ValueCondition, "IsEqual", {
  53004. /**
  53005. * returns the number for IsEqual
  53006. */
  53007. get: function () {
  53008. return ValueCondition._IsEqual;
  53009. },
  53010. enumerable: true,
  53011. configurable: true
  53012. });
  53013. Object.defineProperty(ValueCondition, "IsDifferent", {
  53014. /**
  53015. * Returns the number for IsDifferent
  53016. */
  53017. get: function () {
  53018. return ValueCondition._IsDifferent;
  53019. },
  53020. enumerable: true,
  53021. configurable: true
  53022. });
  53023. Object.defineProperty(ValueCondition, "IsGreater", {
  53024. /**
  53025. * Returns the number for IsGreater
  53026. */
  53027. get: function () {
  53028. return ValueCondition._IsGreater;
  53029. },
  53030. enumerable: true,
  53031. configurable: true
  53032. });
  53033. Object.defineProperty(ValueCondition, "IsLesser", {
  53034. /**
  53035. * Returns the number for IsLesser
  53036. */
  53037. get: function () {
  53038. return ValueCondition._IsLesser;
  53039. },
  53040. enumerable: true,
  53041. configurable: true
  53042. });
  53043. /**
  53044. * Compares the given value with the property value for the specified conditional operator
  53045. * @returns the result of the comparison
  53046. */
  53047. ValueCondition.prototype.isValid = function () {
  53048. switch (this.operator) {
  53049. case ValueCondition.IsGreater:
  53050. return this._effectiveTarget[this._property] > this.value;
  53051. case ValueCondition.IsLesser:
  53052. return this._effectiveTarget[this._property] < this.value;
  53053. case ValueCondition.IsEqual:
  53054. case ValueCondition.IsDifferent:
  53055. var check;
  53056. if (this.value.equals) {
  53057. check = this.value.equals(this._effectiveTarget[this._property]);
  53058. }
  53059. else {
  53060. check = this.value === this._effectiveTarget[this._property];
  53061. }
  53062. return this.operator === ValueCondition.IsEqual ? check : !check;
  53063. }
  53064. return false;
  53065. };
  53066. /**
  53067. * Serialize the ValueCondition into a JSON compatible object
  53068. * @returns serialization object
  53069. */
  53070. ValueCondition.prototype.serialize = function () {
  53071. return this._serialize({
  53072. name: "ValueCondition",
  53073. properties: [
  53074. BABYLON.Action._GetTargetProperty(this._target),
  53075. { name: "propertyPath", value: this.propertyPath },
  53076. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53077. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53078. ]
  53079. });
  53080. };
  53081. /**
  53082. * Gets the name of the conditional operator for the ValueCondition
  53083. * @param operator the conditional operator
  53084. * @returns the name
  53085. */
  53086. ValueCondition.GetOperatorName = function (operator) {
  53087. switch (operator) {
  53088. case ValueCondition._IsEqual: return "IsEqual";
  53089. case ValueCondition._IsDifferent: return "IsDifferent";
  53090. case ValueCondition._IsGreater: return "IsGreater";
  53091. case ValueCondition._IsLesser: return "IsLesser";
  53092. default: return "";
  53093. }
  53094. };
  53095. /**
  53096. * Internal only
  53097. * @hidden
  53098. */
  53099. ValueCondition._IsEqual = 0;
  53100. /**
  53101. * Internal only
  53102. * @hidden
  53103. */
  53104. ValueCondition._IsDifferent = 1;
  53105. /**
  53106. * Internal only
  53107. * @hidden
  53108. */
  53109. ValueCondition._IsGreater = 2;
  53110. /**
  53111. * Internal only
  53112. * @hidden
  53113. */
  53114. ValueCondition._IsLesser = 3;
  53115. return ValueCondition;
  53116. }(Condition));
  53117. BABYLON.ValueCondition = ValueCondition;
  53118. /**
  53119. * Defines a predicate condition as an extension of Condition
  53120. */
  53121. var PredicateCondition = /** @class */ (function (_super) {
  53122. __extends(PredicateCondition, _super);
  53123. /**
  53124. * Creates a new PredicateCondition
  53125. * @param actionManager manager for the action the condition applies to
  53126. * @param predicate defines the predicate function used to validate the condition
  53127. */
  53128. function PredicateCondition(actionManager,
  53129. /** defines the predicate function used to validate the condition */
  53130. predicate) {
  53131. var _this = _super.call(this, actionManager) || this;
  53132. _this.predicate = predicate;
  53133. return _this;
  53134. }
  53135. /**
  53136. * @returns the validity of the predicate condition
  53137. */
  53138. PredicateCondition.prototype.isValid = function () {
  53139. return this.predicate();
  53140. };
  53141. return PredicateCondition;
  53142. }(Condition));
  53143. BABYLON.PredicateCondition = PredicateCondition;
  53144. /**
  53145. * Defines a state condition as an extension of Condition
  53146. */
  53147. var StateCondition = /** @class */ (function (_super) {
  53148. __extends(StateCondition, _super);
  53149. /**
  53150. * Creates a new StateCondition
  53151. * @param actionManager manager for the action the condition applies to
  53152. * @param target of the condition
  53153. * @param value to compare with target state
  53154. */
  53155. function StateCondition(actionManager, target, value) {
  53156. var _this = _super.call(this, actionManager) || this;
  53157. _this.value = value;
  53158. _this._target = target;
  53159. return _this;
  53160. }
  53161. /**
  53162. * @returns the validity of the state
  53163. */
  53164. StateCondition.prototype.isValid = function () {
  53165. return this._target.state === this.value;
  53166. };
  53167. /**
  53168. * Serialize the StateCondition into a JSON compatible object
  53169. * @returns serialization object
  53170. */
  53171. StateCondition.prototype.serialize = function () {
  53172. return this._serialize({
  53173. name: "StateCondition",
  53174. properties: [
  53175. BABYLON.Action._GetTargetProperty(this._target),
  53176. { name: "value", value: this.value }
  53177. ]
  53178. });
  53179. };
  53180. return StateCondition;
  53181. }(Condition));
  53182. BABYLON.StateCondition = StateCondition;
  53183. })(BABYLON || (BABYLON = {}));
  53184. //# sourceMappingURL=babylon.condition.js.map
  53185. var BABYLON;
  53186. (function (BABYLON) {
  53187. /**
  53188. * The action to be carried out following a trigger
  53189. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53190. */
  53191. var Action = /** @class */ (function () {
  53192. /**
  53193. * Creates a new Action
  53194. * @param triggerOptions the trigger, with or without parameters, for the action
  53195. * @param condition an optional determinant of action
  53196. */
  53197. function Action(
  53198. /** the trigger, with or without parameters, for the action */
  53199. triggerOptions, condition) {
  53200. this.triggerOptions = triggerOptions;
  53201. /**
  53202. * An event triggered prior to action being executed.
  53203. */
  53204. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53205. if (triggerOptions.parameter) {
  53206. this.trigger = triggerOptions.trigger;
  53207. this._triggerParameter = triggerOptions.parameter;
  53208. }
  53209. else {
  53210. this.trigger = triggerOptions;
  53211. }
  53212. this._nextActiveAction = this;
  53213. this._condition = condition;
  53214. }
  53215. /**
  53216. * Internal only
  53217. * @hidden
  53218. */
  53219. Action.prototype._prepare = function () {
  53220. };
  53221. /**
  53222. * Gets the trigger parameters
  53223. * @returns the trigger parameters
  53224. */
  53225. Action.prototype.getTriggerParameter = function () {
  53226. return this._triggerParameter;
  53227. };
  53228. /**
  53229. * Internal only - executes current action event
  53230. * @hidden
  53231. */
  53232. Action.prototype._executeCurrent = function (evt) {
  53233. if (this._nextActiveAction._condition) {
  53234. var condition = this._nextActiveAction._condition;
  53235. var currentRenderId = this._actionManager.getScene().getRenderId();
  53236. // We cache the current evaluation for the current frame
  53237. if (condition._evaluationId === currentRenderId) {
  53238. if (!condition._currentResult) {
  53239. return;
  53240. }
  53241. }
  53242. else {
  53243. condition._evaluationId = currentRenderId;
  53244. if (!condition.isValid()) {
  53245. condition._currentResult = false;
  53246. return;
  53247. }
  53248. condition._currentResult = true;
  53249. }
  53250. }
  53251. this.onBeforeExecuteObservable.notifyObservers(this);
  53252. this._nextActiveAction.execute(evt);
  53253. this.skipToNextActiveAction();
  53254. };
  53255. /**
  53256. * Execute placeholder for child classes
  53257. * @param evt optional action event
  53258. */
  53259. Action.prototype.execute = function (evt) {
  53260. };
  53261. /**
  53262. * Skips to next active action
  53263. */
  53264. Action.prototype.skipToNextActiveAction = function () {
  53265. if (this._nextActiveAction._child) {
  53266. if (!this._nextActiveAction._child._actionManager) {
  53267. this._nextActiveAction._child._actionManager = this._actionManager;
  53268. }
  53269. this._nextActiveAction = this._nextActiveAction._child;
  53270. }
  53271. else {
  53272. this._nextActiveAction = this;
  53273. }
  53274. };
  53275. /**
  53276. * Adds action to chain of actions, may be a DoNothingAction
  53277. * @param action defines the next action to execute
  53278. * @returns The action passed in
  53279. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53280. */
  53281. Action.prototype.then = function (action) {
  53282. this._child = action;
  53283. action._actionManager = this._actionManager;
  53284. action._prepare();
  53285. return action;
  53286. };
  53287. /**
  53288. * Internal only
  53289. * @hidden
  53290. */
  53291. Action.prototype._getProperty = function (propertyPath) {
  53292. return this._actionManager._getProperty(propertyPath);
  53293. };
  53294. /**
  53295. * Internal only
  53296. * @hidden
  53297. */
  53298. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53299. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53300. };
  53301. /**
  53302. * Serialize placeholder for child classes
  53303. * @param parent of child
  53304. * @returns the serialized object
  53305. */
  53306. Action.prototype.serialize = function (parent) {
  53307. };
  53308. /**
  53309. * Internal only called by serialize
  53310. * @hidden
  53311. */
  53312. Action.prototype._serialize = function (serializedAction, parent) {
  53313. var serializationObject = {
  53314. type: 1,
  53315. children: [],
  53316. name: serializedAction.name,
  53317. properties: serializedAction.properties || []
  53318. };
  53319. // Serialize child
  53320. if (this._child) {
  53321. this._child.serialize(serializationObject);
  53322. }
  53323. // Check if "this" has a condition
  53324. if (this._condition) {
  53325. var serializedCondition = this._condition.serialize();
  53326. serializedCondition.children.push(serializationObject);
  53327. if (parent) {
  53328. parent.children.push(serializedCondition);
  53329. }
  53330. return serializedCondition;
  53331. }
  53332. if (parent) {
  53333. parent.children.push(serializationObject);
  53334. }
  53335. return serializationObject;
  53336. };
  53337. /**
  53338. * Internal only
  53339. * @hidden
  53340. */
  53341. Action._SerializeValueAsString = function (value) {
  53342. if (typeof value === "number") {
  53343. return value.toString();
  53344. }
  53345. if (typeof value === "boolean") {
  53346. return value ? "true" : "false";
  53347. }
  53348. if (value instanceof BABYLON.Vector2) {
  53349. return value.x + ", " + value.y;
  53350. }
  53351. if (value instanceof BABYLON.Vector3) {
  53352. return value.x + ", " + value.y + ", " + value.z;
  53353. }
  53354. if (value instanceof BABYLON.Color3) {
  53355. return value.r + ", " + value.g + ", " + value.b;
  53356. }
  53357. if (value instanceof BABYLON.Color4) {
  53358. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53359. }
  53360. return value; // string
  53361. };
  53362. /**
  53363. * Internal only
  53364. * @hidden
  53365. */
  53366. Action._GetTargetProperty = function (target) {
  53367. return {
  53368. name: "target",
  53369. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53370. : target instanceof BABYLON.Light ? "LightProperties"
  53371. : target instanceof BABYLON.Camera ? "CameraProperties"
  53372. : "SceneProperties",
  53373. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53374. };
  53375. };
  53376. return Action;
  53377. }());
  53378. BABYLON.Action = Action;
  53379. })(BABYLON || (BABYLON = {}));
  53380. //# sourceMappingURL=babylon.action.js.map
  53381. var BABYLON;
  53382. (function (BABYLON) {
  53383. /**
  53384. * ActionEvent is the event being sent when an action is triggered.
  53385. */
  53386. var ActionEvent = /** @class */ (function () {
  53387. /**
  53388. * Creates a new ActionEvent
  53389. * @param source The mesh or sprite that triggered the action
  53390. * @param pointerX The X mouse cursor position at the time of the event
  53391. * @param pointerY The Y mouse cursor position at the time of the event
  53392. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53393. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53394. * @param additionalData additional data for the event
  53395. */
  53396. function ActionEvent(
  53397. /** The mesh or sprite that triggered the action */
  53398. source,
  53399. /** The X mouse cursor position at the time of the event */
  53400. pointerX,
  53401. /** The Y mouse cursor position at the time of the event */
  53402. pointerY,
  53403. /** The mesh that is currently pointed at (can be null) */
  53404. meshUnderPointer,
  53405. /** the original (browser) event that triggered the ActionEvent */
  53406. sourceEvent,
  53407. /** additional data for the event */
  53408. additionalData) {
  53409. this.source = source;
  53410. this.pointerX = pointerX;
  53411. this.pointerY = pointerY;
  53412. this.meshUnderPointer = meshUnderPointer;
  53413. this.sourceEvent = sourceEvent;
  53414. this.additionalData = additionalData;
  53415. }
  53416. /**
  53417. * Helper function to auto-create an ActionEvent from a source mesh.
  53418. * @param source The source mesh that triggered the event
  53419. * @param evt The original (browser) event
  53420. * @param additionalData additional data for the event
  53421. * @returns the new ActionEvent
  53422. */
  53423. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53424. var scene = source.getScene();
  53425. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53426. };
  53427. /**
  53428. * Helper function to auto-create an ActionEvent from a source sprite
  53429. * @param source The source sprite that triggered the event
  53430. * @param scene Scene associated with the sprite
  53431. * @param evt The original (browser) event
  53432. * @param additionalData additional data for the event
  53433. * @returns the new ActionEvent
  53434. */
  53435. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53436. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53437. };
  53438. /**
  53439. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53440. * @param scene the scene where the event occurred
  53441. * @param evt The original (browser) event
  53442. * @returns the new ActionEvent
  53443. */
  53444. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53445. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53446. };
  53447. /**
  53448. * Helper function to auto-create an ActionEvent from a primitive
  53449. * @param prim defines the target primitive
  53450. * @param pointerPos defines the pointer position
  53451. * @param evt The original (browser) event
  53452. * @param additionalData additional data for the event
  53453. * @returns the new ActionEvent
  53454. */
  53455. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53456. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53457. };
  53458. return ActionEvent;
  53459. }());
  53460. BABYLON.ActionEvent = ActionEvent;
  53461. /**
  53462. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53463. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53464. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53465. */
  53466. var ActionManager = /** @class */ (function () {
  53467. /**
  53468. * Creates a new action manager
  53469. * @param scene defines the hosting scene
  53470. */
  53471. function ActionManager(scene) {
  53472. // Members
  53473. /** Gets the list of actions */
  53474. this.actions = new Array();
  53475. /** Gets the cursor to use when hovering items */
  53476. this.hoverCursor = '';
  53477. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53478. scene._actionManagers.push(this);
  53479. }
  53480. Object.defineProperty(ActionManager, "NothingTrigger", {
  53481. /**
  53482. * Nothing
  53483. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53484. */
  53485. get: function () {
  53486. return ActionManager._NothingTrigger;
  53487. },
  53488. enumerable: true,
  53489. configurable: true
  53490. });
  53491. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53492. /**
  53493. * On pick
  53494. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53495. */
  53496. get: function () {
  53497. return ActionManager._OnPickTrigger;
  53498. },
  53499. enumerable: true,
  53500. configurable: true
  53501. });
  53502. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53503. /**
  53504. * On left pick
  53505. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53506. */
  53507. get: function () {
  53508. return ActionManager._OnLeftPickTrigger;
  53509. },
  53510. enumerable: true,
  53511. configurable: true
  53512. });
  53513. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53514. /**
  53515. * On right pick
  53516. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53517. */
  53518. get: function () {
  53519. return ActionManager._OnRightPickTrigger;
  53520. },
  53521. enumerable: true,
  53522. configurable: true
  53523. });
  53524. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53525. /**
  53526. * On center pick
  53527. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53528. */
  53529. get: function () {
  53530. return ActionManager._OnCenterPickTrigger;
  53531. },
  53532. enumerable: true,
  53533. configurable: true
  53534. });
  53535. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53536. /**
  53537. * On pick down
  53538. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53539. */
  53540. get: function () {
  53541. return ActionManager._OnPickDownTrigger;
  53542. },
  53543. enumerable: true,
  53544. configurable: true
  53545. });
  53546. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53547. /**
  53548. * On double pick
  53549. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53550. */
  53551. get: function () {
  53552. return ActionManager._OnDoublePickTrigger;
  53553. },
  53554. enumerable: true,
  53555. configurable: true
  53556. });
  53557. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53558. /**
  53559. * On pick up
  53560. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53561. */
  53562. get: function () {
  53563. return ActionManager._OnPickUpTrigger;
  53564. },
  53565. enumerable: true,
  53566. configurable: true
  53567. });
  53568. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53569. /**
  53570. * On pick out.
  53571. * This trigger will only be raised if you also declared a OnPickDown
  53572. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53573. */
  53574. get: function () {
  53575. return ActionManager._OnPickOutTrigger;
  53576. },
  53577. enumerable: true,
  53578. configurable: true
  53579. });
  53580. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53581. /**
  53582. * On long press
  53583. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53584. */
  53585. get: function () {
  53586. return ActionManager._OnLongPressTrigger;
  53587. },
  53588. enumerable: true,
  53589. configurable: true
  53590. });
  53591. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53592. /**
  53593. * On pointer over
  53594. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53595. */
  53596. get: function () {
  53597. return ActionManager._OnPointerOverTrigger;
  53598. },
  53599. enumerable: true,
  53600. configurable: true
  53601. });
  53602. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53603. /**
  53604. * On pointer out
  53605. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53606. */
  53607. get: function () {
  53608. return ActionManager._OnPointerOutTrigger;
  53609. },
  53610. enumerable: true,
  53611. configurable: true
  53612. });
  53613. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53614. /**
  53615. * On every frame
  53616. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53617. */
  53618. get: function () {
  53619. return ActionManager._OnEveryFrameTrigger;
  53620. },
  53621. enumerable: true,
  53622. configurable: true
  53623. });
  53624. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53625. /**
  53626. * On intersection enter
  53627. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53628. */
  53629. get: function () {
  53630. return ActionManager._OnIntersectionEnterTrigger;
  53631. },
  53632. enumerable: true,
  53633. configurable: true
  53634. });
  53635. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53636. /**
  53637. * On intersection exit
  53638. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53639. */
  53640. get: function () {
  53641. return ActionManager._OnIntersectionExitTrigger;
  53642. },
  53643. enumerable: true,
  53644. configurable: true
  53645. });
  53646. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53647. /**
  53648. * On key down
  53649. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53650. */
  53651. get: function () {
  53652. return ActionManager._OnKeyDownTrigger;
  53653. },
  53654. enumerable: true,
  53655. configurable: true
  53656. });
  53657. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53658. /**
  53659. * On key up
  53660. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53661. */
  53662. get: function () {
  53663. return ActionManager._OnKeyUpTrigger;
  53664. },
  53665. enumerable: true,
  53666. configurable: true
  53667. });
  53668. // Methods
  53669. /**
  53670. * Releases all associated resources
  53671. */
  53672. ActionManager.prototype.dispose = function () {
  53673. var index = this._scene._actionManagers.indexOf(this);
  53674. for (var i = 0; i < this.actions.length; i++) {
  53675. var action = this.actions[i];
  53676. ActionManager.Triggers[action.trigger]--;
  53677. if (ActionManager.Triggers[action.trigger] === 0) {
  53678. delete ActionManager.Triggers[action.trigger];
  53679. }
  53680. }
  53681. if (index > -1) {
  53682. this._scene._actionManagers.splice(index, 1);
  53683. }
  53684. };
  53685. /**
  53686. * Gets hosting scene
  53687. * @returns the hosting scene
  53688. */
  53689. ActionManager.prototype.getScene = function () {
  53690. return this._scene;
  53691. };
  53692. /**
  53693. * Does this action manager handles actions of any of the given triggers
  53694. * @param triggers defines the triggers to be tested
  53695. * @return a boolean indicating whether one (or more) of the triggers is handled
  53696. */
  53697. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53698. for (var index = 0; index < this.actions.length; index++) {
  53699. var action = this.actions[index];
  53700. if (triggers.indexOf(action.trigger) > -1) {
  53701. return true;
  53702. }
  53703. }
  53704. return false;
  53705. };
  53706. /**
  53707. * Does this action manager handles actions of a given trigger
  53708. * @param trigger defines the trigger to be tested
  53709. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53710. * @return whether the trigger is handled
  53711. */
  53712. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53713. for (var index = 0; index < this.actions.length; index++) {
  53714. var action = this.actions[index];
  53715. if (action.trigger === trigger) {
  53716. if (parameterPredicate) {
  53717. if (parameterPredicate(action.getTriggerParameter())) {
  53718. return true;
  53719. }
  53720. }
  53721. else {
  53722. return true;
  53723. }
  53724. }
  53725. }
  53726. return false;
  53727. };
  53728. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53729. /**
  53730. * Does this action manager has pointer triggers
  53731. */
  53732. get: function () {
  53733. for (var index = 0; index < this.actions.length; index++) {
  53734. var action = this.actions[index];
  53735. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53736. return true;
  53737. }
  53738. }
  53739. return false;
  53740. },
  53741. enumerable: true,
  53742. configurable: true
  53743. });
  53744. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53745. /**
  53746. * Does this action manager has pick triggers
  53747. */
  53748. get: function () {
  53749. for (var index = 0; index < this.actions.length; index++) {
  53750. var action = this.actions[index];
  53751. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53752. return true;
  53753. }
  53754. }
  53755. return false;
  53756. },
  53757. enumerable: true,
  53758. configurable: true
  53759. });
  53760. Object.defineProperty(ActionManager, "HasTriggers", {
  53761. /**
  53762. * Does exist one action manager with at least one trigger
  53763. **/
  53764. get: function () {
  53765. for (var t in ActionManager.Triggers) {
  53766. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53767. return true;
  53768. }
  53769. }
  53770. return false;
  53771. },
  53772. enumerable: true,
  53773. configurable: true
  53774. });
  53775. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53776. /**
  53777. * Does exist one action manager with at least one pick trigger
  53778. **/
  53779. get: function () {
  53780. for (var t in ActionManager.Triggers) {
  53781. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53782. var t_int = parseInt(t);
  53783. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53784. return true;
  53785. }
  53786. }
  53787. }
  53788. return false;
  53789. },
  53790. enumerable: true,
  53791. configurable: true
  53792. });
  53793. /**
  53794. * Does exist one action manager that handles actions of a given trigger
  53795. * @param trigger defines the trigger to be tested
  53796. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53797. **/
  53798. ActionManager.HasSpecificTrigger = function (trigger) {
  53799. for (var t in ActionManager.Triggers) {
  53800. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53801. var t_int = parseInt(t);
  53802. if (t_int === trigger) {
  53803. return true;
  53804. }
  53805. }
  53806. }
  53807. return false;
  53808. };
  53809. /**
  53810. * Registers an action to this action manager
  53811. * @param action defines the action to be registered
  53812. * @return the action amended (prepared) after registration
  53813. */
  53814. ActionManager.prototype.registerAction = function (action) {
  53815. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53816. if (this.getScene().actionManager !== this) {
  53817. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53818. return null;
  53819. }
  53820. }
  53821. this.actions.push(action);
  53822. if (ActionManager.Triggers[action.trigger]) {
  53823. ActionManager.Triggers[action.trigger]++;
  53824. }
  53825. else {
  53826. ActionManager.Triggers[action.trigger] = 1;
  53827. }
  53828. action._actionManager = this;
  53829. action._prepare();
  53830. return action;
  53831. };
  53832. /**
  53833. * Unregisters an action to this action manager
  53834. * @param action defines the action to be unregistered
  53835. * @return a boolean indicating whether the action has been unregistered
  53836. */
  53837. ActionManager.prototype.unregisterAction = function (action) {
  53838. var index = this.actions.indexOf(action);
  53839. if (index !== -1) {
  53840. this.actions.splice(index, 1);
  53841. ActionManager.Triggers[action.trigger] -= 1;
  53842. if (ActionManager.Triggers[action.trigger] === 0) {
  53843. delete ActionManager.Triggers[action.trigger];
  53844. }
  53845. delete action._actionManager;
  53846. return true;
  53847. }
  53848. return false;
  53849. };
  53850. /**
  53851. * Process a specific trigger
  53852. * @param trigger defines the trigger to process
  53853. * @param evt defines the event details to be processed
  53854. */
  53855. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53856. for (var index = 0; index < this.actions.length; index++) {
  53857. var action = this.actions[index];
  53858. if (action.trigger === trigger) {
  53859. if (evt) {
  53860. if (trigger === ActionManager.OnKeyUpTrigger
  53861. || trigger === ActionManager.OnKeyDownTrigger) {
  53862. var parameter = action.getTriggerParameter();
  53863. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53864. if (!parameter.toLowerCase) {
  53865. continue;
  53866. }
  53867. var lowerCase = parameter.toLowerCase();
  53868. if (lowerCase !== evt.sourceEvent.key) {
  53869. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53870. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53871. if (actualkey !== lowerCase) {
  53872. continue;
  53873. }
  53874. }
  53875. }
  53876. }
  53877. }
  53878. action._executeCurrent(evt);
  53879. }
  53880. }
  53881. };
  53882. /** @hidden */
  53883. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53884. var properties = propertyPath.split(".");
  53885. for (var index = 0; index < properties.length - 1; index++) {
  53886. target = target[properties[index]];
  53887. }
  53888. return target;
  53889. };
  53890. /** @hidden */
  53891. ActionManager.prototype._getProperty = function (propertyPath) {
  53892. var properties = propertyPath.split(".");
  53893. return properties[properties.length - 1];
  53894. };
  53895. /**
  53896. * Serialize this manager to a JSON object
  53897. * @param name defines the property name to store this manager
  53898. * @returns a JSON representation of this manager
  53899. */
  53900. ActionManager.prototype.serialize = function (name) {
  53901. var root = {
  53902. children: new Array(),
  53903. name: name,
  53904. type: 3,
  53905. properties: new Array() // Empty for root but required
  53906. };
  53907. for (var i = 0; i < this.actions.length; i++) {
  53908. var triggerObject = {
  53909. type: 0,
  53910. children: new Array(),
  53911. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53912. properties: new Array()
  53913. };
  53914. var triggerOptions = this.actions[i].triggerOptions;
  53915. if (triggerOptions && typeof triggerOptions !== "number") {
  53916. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53917. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53918. }
  53919. else {
  53920. var parameter = {};
  53921. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53922. if (triggerOptions.parameter.mesh) {
  53923. parameter._meshId = triggerOptions.parameter.mesh.id;
  53924. }
  53925. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53926. }
  53927. }
  53928. // Serialize child action, recursively
  53929. this.actions[i].serialize(triggerObject);
  53930. // Add serialized trigger
  53931. root.children.push(triggerObject);
  53932. }
  53933. return root;
  53934. };
  53935. /**
  53936. * Creates a new ActionManager from a JSON data
  53937. * @param parsedActions defines the JSON data to read from
  53938. * @param object defines the hosting mesh
  53939. * @param scene defines the hosting scene
  53940. */
  53941. ActionManager.Parse = function (parsedActions, object, scene) {
  53942. var actionManager = new ActionManager(scene);
  53943. if (object === null)
  53944. scene.actionManager = actionManager;
  53945. else
  53946. object.actionManager = actionManager;
  53947. // instanciate a new object
  53948. var instanciate = function (name, params) {
  53949. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53950. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53951. newInstance.constructor.apply(newInstance, params);
  53952. return newInstance;
  53953. };
  53954. var parseParameter = function (name, value, target, propertyPath) {
  53955. if (propertyPath === null) {
  53956. // String, boolean or float
  53957. var floatValue = parseFloat(value);
  53958. if (value === "true" || value === "false")
  53959. return value === "true";
  53960. else
  53961. return isNaN(floatValue) ? value : floatValue;
  53962. }
  53963. var effectiveTarget = propertyPath.split(".");
  53964. var values = value.split(",");
  53965. // Get effective Target
  53966. for (var i = 0; i < effectiveTarget.length; i++) {
  53967. target = target[effectiveTarget[i]];
  53968. }
  53969. // Return appropriate value with its type
  53970. if (typeof (target) === "boolean")
  53971. return values[0] === "true";
  53972. if (typeof (target) === "string")
  53973. return values[0];
  53974. // Parameters with multiple values such as Vector3 etc.
  53975. var split = new Array();
  53976. for (var i = 0; i < values.length; i++)
  53977. split.push(parseFloat(values[i]));
  53978. if (target instanceof BABYLON.Vector3)
  53979. return BABYLON.Vector3.FromArray(split);
  53980. if (target instanceof BABYLON.Vector4)
  53981. return BABYLON.Vector4.FromArray(split);
  53982. if (target instanceof BABYLON.Color3)
  53983. return BABYLON.Color3.FromArray(split);
  53984. if (target instanceof BABYLON.Color4)
  53985. return BABYLON.Color4.FromArray(split);
  53986. return parseFloat(values[0]);
  53987. };
  53988. // traverse graph per trigger
  53989. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53990. if (combineArray === void 0) { combineArray = null; }
  53991. if (parsedAction.detached)
  53992. return;
  53993. var parameters = new Array();
  53994. var target = null;
  53995. var propertyPath = null;
  53996. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53997. // Parameters
  53998. if (parsedAction.type === 2)
  53999. parameters.push(actionManager);
  54000. else
  54001. parameters.push(trigger);
  54002. if (combine) {
  54003. var actions = new Array();
  54004. for (var j = 0; j < parsedAction.combine.length; j++) {
  54005. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54006. }
  54007. parameters.push(actions);
  54008. }
  54009. else {
  54010. for (var i = 0; i < parsedAction.properties.length; i++) {
  54011. var value = parsedAction.properties[i].value;
  54012. var name = parsedAction.properties[i].name;
  54013. var targetType = parsedAction.properties[i].targetType;
  54014. if (name === "target")
  54015. if (targetType !== null && targetType === "SceneProperties")
  54016. value = target = scene;
  54017. else
  54018. value = target = scene.getNodeByName(value);
  54019. else if (name === "parent")
  54020. value = scene.getNodeByName(value);
  54021. else if (name === "sound")
  54022. value = scene.getSoundByName(value);
  54023. else if (name !== "propertyPath") {
  54024. if (parsedAction.type === 2 && name === "operator")
  54025. value = BABYLON.ValueCondition[value];
  54026. else
  54027. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54028. }
  54029. else {
  54030. propertyPath = value;
  54031. }
  54032. parameters.push(value);
  54033. }
  54034. }
  54035. if (combineArray === null) {
  54036. parameters.push(condition);
  54037. }
  54038. else {
  54039. parameters.push(null);
  54040. }
  54041. // If interpolate value action
  54042. if (parsedAction.name === "InterpolateValueAction") {
  54043. var param = parameters[parameters.length - 2];
  54044. parameters[parameters.length - 1] = param;
  54045. parameters[parameters.length - 2] = condition;
  54046. }
  54047. // Action or condition(s) and not CombineAction
  54048. var newAction = instanciate(parsedAction.name, parameters);
  54049. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54050. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54051. if (action)
  54052. action.then(nothing);
  54053. else
  54054. actionManager.registerAction(nothing);
  54055. action = nothing;
  54056. }
  54057. if (combineArray === null) {
  54058. if (newAction instanceof BABYLON.Condition) {
  54059. condition = newAction;
  54060. newAction = action;
  54061. }
  54062. else {
  54063. condition = null;
  54064. if (action)
  54065. action.then(newAction);
  54066. else
  54067. actionManager.registerAction(newAction);
  54068. }
  54069. }
  54070. else {
  54071. combineArray.push(newAction);
  54072. }
  54073. for (var i = 0; i < parsedAction.children.length; i++)
  54074. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54075. };
  54076. // triggers
  54077. for (var i = 0; i < parsedActions.children.length; i++) {
  54078. var triggerParams;
  54079. var trigger = parsedActions.children[i];
  54080. if (trigger.properties.length > 0) {
  54081. var param = trigger.properties[0].value;
  54082. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54083. if (value._meshId) {
  54084. value.mesh = scene.getMeshByID(value._meshId);
  54085. }
  54086. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54087. }
  54088. else
  54089. triggerParams = ActionManager[trigger.name];
  54090. for (var j = 0; j < trigger.children.length; j++) {
  54091. if (!trigger.detached)
  54092. traverse(trigger.children[j], triggerParams, null, null);
  54093. }
  54094. }
  54095. };
  54096. /**
  54097. * Get a trigger name by index
  54098. * @param trigger defines the trigger index
  54099. * @returns a trigger name
  54100. */
  54101. ActionManager.GetTriggerName = function (trigger) {
  54102. switch (trigger) {
  54103. case 0: return "NothingTrigger";
  54104. case 1: return "OnPickTrigger";
  54105. case 2: return "OnLeftPickTrigger";
  54106. case 3: return "OnRightPickTrigger";
  54107. case 4: return "OnCenterPickTrigger";
  54108. case 5: return "OnPickDownTrigger";
  54109. case 6: return "OnPickUpTrigger";
  54110. case 7: return "OnLongPressTrigger";
  54111. case 8: return "OnPointerOverTrigger";
  54112. case 9: return "OnPointerOutTrigger";
  54113. case 10: return "OnEveryFrameTrigger";
  54114. case 11: return "OnIntersectionEnterTrigger";
  54115. case 12: return "OnIntersectionExitTrigger";
  54116. case 13: return "OnKeyDownTrigger";
  54117. case 14: return "OnKeyUpTrigger";
  54118. case 15: return "OnPickOutTrigger";
  54119. default: return "";
  54120. }
  54121. };
  54122. // Statics
  54123. ActionManager._NothingTrigger = 0;
  54124. ActionManager._OnPickTrigger = 1;
  54125. ActionManager._OnLeftPickTrigger = 2;
  54126. ActionManager._OnRightPickTrigger = 3;
  54127. ActionManager._OnCenterPickTrigger = 4;
  54128. ActionManager._OnPickDownTrigger = 5;
  54129. ActionManager._OnDoublePickTrigger = 6;
  54130. ActionManager._OnPickUpTrigger = 7;
  54131. ActionManager._OnLongPressTrigger = 8;
  54132. ActionManager._OnPointerOverTrigger = 9;
  54133. ActionManager._OnPointerOutTrigger = 10;
  54134. ActionManager._OnEveryFrameTrigger = 11;
  54135. ActionManager._OnIntersectionEnterTrigger = 12;
  54136. ActionManager._OnIntersectionExitTrigger = 13;
  54137. ActionManager._OnKeyDownTrigger = 14;
  54138. ActionManager._OnKeyUpTrigger = 15;
  54139. ActionManager._OnPickOutTrigger = 16;
  54140. /** Gets the list of active triggers */
  54141. ActionManager.Triggers = {};
  54142. return ActionManager;
  54143. }());
  54144. BABYLON.ActionManager = ActionManager;
  54145. })(BABYLON || (BABYLON = {}));
  54146. //# sourceMappingURL=babylon.actionManager.js.map
  54147. var BABYLON;
  54148. (function (BABYLON) {
  54149. var InterpolateValueAction = /** @class */ (function (_super) {
  54150. __extends(InterpolateValueAction, _super);
  54151. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54152. if (duration === void 0) { duration = 1000; }
  54153. var _this = _super.call(this, triggerOptions, condition) || this;
  54154. _this.propertyPath = propertyPath;
  54155. _this.value = value;
  54156. _this.duration = duration;
  54157. _this.stopOtherAnimations = stopOtherAnimations;
  54158. _this.onInterpolationDone = onInterpolationDone;
  54159. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54160. _this._target = _this._effectiveTarget = target;
  54161. return _this;
  54162. }
  54163. InterpolateValueAction.prototype._prepare = function () {
  54164. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54165. this._property = this._getProperty(this.propertyPath);
  54166. };
  54167. InterpolateValueAction.prototype.execute = function () {
  54168. var _this = this;
  54169. var scene = this._actionManager.getScene();
  54170. var keys = [
  54171. {
  54172. frame: 0,
  54173. value: this._effectiveTarget[this._property]
  54174. }, {
  54175. frame: 100,
  54176. value: this.value
  54177. }
  54178. ];
  54179. var dataType;
  54180. if (typeof this.value === "number") {
  54181. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54182. }
  54183. else if (this.value instanceof BABYLON.Color3) {
  54184. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54185. }
  54186. else if (this.value instanceof BABYLON.Vector3) {
  54187. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54188. }
  54189. else if (this.value instanceof BABYLON.Matrix) {
  54190. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54191. }
  54192. else if (this.value instanceof BABYLON.Quaternion) {
  54193. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54194. }
  54195. else {
  54196. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54197. return;
  54198. }
  54199. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54200. animation.setKeys(keys);
  54201. if (this.stopOtherAnimations) {
  54202. scene.stopAnimation(this._effectiveTarget);
  54203. }
  54204. var wrapper = function () {
  54205. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54206. if (_this.onInterpolationDone) {
  54207. _this.onInterpolationDone();
  54208. }
  54209. };
  54210. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54211. };
  54212. InterpolateValueAction.prototype.serialize = function (parent) {
  54213. return _super.prototype._serialize.call(this, {
  54214. name: "InterpolateValueAction",
  54215. properties: [
  54216. BABYLON.Action._GetTargetProperty(this._target),
  54217. { name: "propertyPath", value: this.propertyPath },
  54218. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54219. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54220. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54221. ]
  54222. }, parent);
  54223. };
  54224. return InterpolateValueAction;
  54225. }(BABYLON.Action));
  54226. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54227. })(BABYLON || (BABYLON = {}));
  54228. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54229. var BABYLON;
  54230. (function (BABYLON) {
  54231. var SwitchBooleanAction = /** @class */ (function (_super) {
  54232. __extends(SwitchBooleanAction, _super);
  54233. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54234. var _this = _super.call(this, triggerOptions, condition) || this;
  54235. _this.propertyPath = propertyPath;
  54236. _this._target = _this._effectiveTarget = target;
  54237. return _this;
  54238. }
  54239. SwitchBooleanAction.prototype._prepare = function () {
  54240. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54241. this._property = this._getProperty(this.propertyPath);
  54242. };
  54243. SwitchBooleanAction.prototype.execute = function () {
  54244. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54245. };
  54246. SwitchBooleanAction.prototype.serialize = function (parent) {
  54247. return _super.prototype._serialize.call(this, {
  54248. name: "SwitchBooleanAction",
  54249. properties: [
  54250. BABYLON.Action._GetTargetProperty(this._target),
  54251. { name: "propertyPath", value: this.propertyPath }
  54252. ]
  54253. }, parent);
  54254. };
  54255. return SwitchBooleanAction;
  54256. }(BABYLON.Action));
  54257. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54258. var SetStateAction = /** @class */ (function (_super) {
  54259. __extends(SetStateAction, _super);
  54260. function SetStateAction(triggerOptions, target, value, condition) {
  54261. var _this = _super.call(this, triggerOptions, condition) || this;
  54262. _this.value = value;
  54263. _this._target = target;
  54264. return _this;
  54265. }
  54266. SetStateAction.prototype.execute = function () {
  54267. this._target.state = this.value;
  54268. };
  54269. SetStateAction.prototype.serialize = function (parent) {
  54270. return _super.prototype._serialize.call(this, {
  54271. name: "SetStateAction",
  54272. properties: [
  54273. BABYLON.Action._GetTargetProperty(this._target),
  54274. { name: "value", value: this.value }
  54275. ]
  54276. }, parent);
  54277. };
  54278. return SetStateAction;
  54279. }(BABYLON.Action));
  54280. BABYLON.SetStateAction = SetStateAction;
  54281. var SetValueAction = /** @class */ (function (_super) {
  54282. __extends(SetValueAction, _super);
  54283. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54284. var _this = _super.call(this, triggerOptions, condition) || this;
  54285. _this.propertyPath = propertyPath;
  54286. _this.value = value;
  54287. _this._target = _this._effectiveTarget = target;
  54288. return _this;
  54289. }
  54290. SetValueAction.prototype._prepare = function () {
  54291. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54292. this._property = this._getProperty(this.propertyPath);
  54293. };
  54294. SetValueAction.prototype.execute = function () {
  54295. this._effectiveTarget[this._property] = this.value;
  54296. if (this._target.markAsDirty) {
  54297. this._target.markAsDirty(this._property);
  54298. }
  54299. };
  54300. SetValueAction.prototype.serialize = function (parent) {
  54301. return _super.prototype._serialize.call(this, {
  54302. name: "SetValueAction",
  54303. properties: [
  54304. BABYLON.Action._GetTargetProperty(this._target),
  54305. { name: "propertyPath", value: this.propertyPath },
  54306. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54307. ]
  54308. }, parent);
  54309. };
  54310. return SetValueAction;
  54311. }(BABYLON.Action));
  54312. BABYLON.SetValueAction = SetValueAction;
  54313. var IncrementValueAction = /** @class */ (function (_super) {
  54314. __extends(IncrementValueAction, _super);
  54315. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54316. var _this = _super.call(this, triggerOptions, condition) || this;
  54317. _this.propertyPath = propertyPath;
  54318. _this.value = value;
  54319. _this._target = _this._effectiveTarget = target;
  54320. return _this;
  54321. }
  54322. IncrementValueAction.prototype._prepare = function () {
  54323. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54324. this._property = this._getProperty(this.propertyPath);
  54325. if (typeof this._effectiveTarget[this._property] !== "number") {
  54326. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54327. }
  54328. };
  54329. IncrementValueAction.prototype.execute = function () {
  54330. this._effectiveTarget[this._property] += this.value;
  54331. if (this._target.markAsDirty) {
  54332. this._target.markAsDirty(this._property);
  54333. }
  54334. };
  54335. IncrementValueAction.prototype.serialize = function (parent) {
  54336. return _super.prototype._serialize.call(this, {
  54337. name: "IncrementValueAction",
  54338. properties: [
  54339. BABYLON.Action._GetTargetProperty(this._target),
  54340. { name: "propertyPath", value: this.propertyPath },
  54341. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54342. ]
  54343. }, parent);
  54344. };
  54345. return IncrementValueAction;
  54346. }(BABYLON.Action));
  54347. BABYLON.IncrementValueAction = IncrementValueAction;
  54348. var PlayAnimationAction = /** @class */ (function (_super) {
  54349. __extends(PlayAnimationAction, _super);
  54350. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54351. var _this = _super.call(this, triggerOptions, condition) || this;
  54352. _this.from = from;
  54353. _this.to = to;
  54354. _this.loop = loop;
  54355. _this._target = target;
  54356. return _this;
  54357. }
  54358. PlayAnimationAction.prototype._prepare = function () {
  54359. };
  54360. PlayAnimationAction.prototype.execute = function () {
  54361. var scene = this._actionManager.getScene();
  54362. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54363. };
  54364. PlayAnimationAction.prototype.serialize = function (parent) {
  54365. return _super.prototype._serialize.call(this, {
  54366. name: "PlayAnimationAction",
  54367. properties: [
  54368. BABYLON.Action._GetTargetProperty(this._target),
  54369. { name: "from", value: String(this.from) },
  54370. { name: "to", value: String(this.to) },
  54371. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54372. ]
  54373. }, parent);
  54374. };
  54375. return PlayAnimationAction;
  54376. }(BABYLON.Action));
  54377. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54378. var StopAnimationAction = /** @class */ (function (_super) {
  54379. __extends(StopAnimationAction, _super);
  54380. function StopAnimationAction(triggerOptions, target, condition) {
  54381. var _this = _super.call(this, triggerOptions, condition) || this;
  54382. _this._target = target;
  54383. return _this;
  54384. }
  54385. StopAnimationAction.prototype._prepare = function () {
  54386. };
  54387. StopAnimationAction.prototype.execute = function () {
  54388. var scene = this._actionManager.getScene();
  54389. scene.stopAnimation(this._target);
  54390. };
  54391. StopAnimationAction.prototype.serialize = function (parent) {
  54392. return _super.prototype._serialize.call(this, {
  54393. name: "StopAnimationAction",
  54394. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54395. }, parent);
  54396. };
  54397. return StopAnimationAction;
  54398. }(BABYLON.Action));
  54399. BABYLON.StopAnimationAction = StopAnimationAction;
  54400. var DoNothingAction = /** @class */ (function (_super) {
  54401. __extends(DoNothingAction, _super);
  54402. function DoNothingAction(triggerOptions, condition) {
  54403. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54404. return _super.call(this, triggerOptions, condition) || this;
  54405. }
  54406. DoNothingAction.prototype.execute = function () {
  54407. };
  54408. DoNothingAction.prototype.serialize = function (parent) {
  54409. return _super.prototype._serialize.call(this, {
  54410. name: "DoNothingAction",
  54411. properties: []
  54412. }, parent);
  54413. };
  54414. return DoNothingAction;
  54415. }(BABYLON.Action));
  54416. BABYLON.DoNothingAction = DoNothingAction;
  54417. var CombineAction = /** @class */ (function (_super) {
  54418. __extends(CombineAction, _super);
  54419. function CombineAction(triggerOptions, children, condition) {
  54420. var _this = _super.call(this, triggerOptions, condition) || this;
  54421. _this.children = children;
  54422. return _this;
  54423. }
  54424. CombineAction.prototype._prepare = function () {
  54425. for (var index = 0; index < this.children.length; index++) {
  54426. this.children[index]._actionManager = this._actionManager;
  54427. this.children[index]._prepare();
  54428. }
  54429. };
  54430. CombineAction.prototype.execute = function (evt) {
  54431. for (var index = 0; index < this.children.length; index++) {
  54432. this.children[index].execute(evt);
  54433. }
  54434. };
  54435. CombineAction.prototype.serialize = function (parent) {
  54436. var serializationObject = _super.prototype._serialize.call(this, {
  54437. name: "CombineAction",
  54438. properties: [],
  54439. combine: []
  54440. }, parent);
  54441. for (var i = 0; i < this.children.length; i++) {
  54442. serializationObject.combine.push(this.children[i].serialize(null));
  54443. }
  54444. return serializationObject;
  54445. };
  54446. return CombineAction;
  54447. }(BABYLON.Action));
  54448. BABYLON.CombineAction = CombineAction;
  54449. var ExecuteCodeAction = /** @class */ (function (_super) {
  54450. __extends(ExecuteCodeAction, _super);
  54451. function ExecuteCodeAction(triggerOptions, func, condition) {
  54452. var _this = _super.call(this, triggerOptions, condition) || this;
  54453. _this.func = func;
  54454. return _this;
  54455. }
  54456. ExecuteCodeAction.prototype.execute = function (evt) {
  54457. this.func(evt);
  54458. };
  54459. return ExecuteCodeAction;
  54460. }(BABYLON.Action));
  54461. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54462. var SetParentAction = /** @class */ (function (_super) {
  54463. __extends(SetParentAction, _super);
  54464. function SetParentAction(triggerOptions, target, parent, condition) {
  54465. var _this = _super.call(this, triggerOptions, condition) || this;
  54466. _this._target = target;
  54467. _this._parent = parent;
  54468. return _this;
  54469. }
  54470. SetParentAction.prototype._prepare = function () {
  54471. };
  54472. SetParentAction.prototype.execute = function () {
  54473. if (this._target.parent === this._parent) {
  54474. return;
  54475. }
  54476. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54477. invertParentWorldMatrix.invert();
  54478. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54479. this._target.parent = this._parent;
  54480. };
  54481. SetParentAction.prototype.serialize = function (parent) {
  54482. return _super.prototype._serialize.call(this, {
  54483. name: "SetParentAction",
  54484. properties: [
  54485. BABYLON.Action._GetTargetProperty(this._target),
  54486. BABYLON.Action._GetTargetProperty(this._parent),
  54487. ]
  54488. }, parent);
  54489. };
  54490. return SetParentAction;
  54491. }(BABYLON.Action));
  54492. BABYLON.SetParentAction = SetParentAction;
  54493. var PlaySoundAction = /** @class */ (function (_super) {
  54494. __extends(PlaySoundAction, _super);
  54495. function PlaySoundAction(triggerOptions, sound, condition) {
  54496. var _this = _super.call(this, triggerOptions, condition) || this;
  54497. _this._sound = sound;
  54498. return _this;
  54499. }
  54500. PlaySoundAction.prototype._prepare = function () {
  54501. };
  54502. PlaySoundAction.prototype.execute = function () {
  54503. if (this._sound !== undefined)
  54504. this._sound.play();
  54505. };
  54506. PlaySoundAction.prototype.serialize = function (parent) {
  54507. return _super.prototype._serialize.call(this, {
  54508. name: "PlaySoundAction",
  54509. properties: [{ name: "sound", value: this._sound.name }]
  54510. }, parent);
  54511. };
  54512. return PlaySoundAction;
  54513. }(BABYLON.Action));
  54514. BABYLON.PlaySoundAction = PlaySoundAction;
  54515. var StopSoundAction = /** @class */ (function (_super) {
  54516. __extends(StopSoundAction, _super);
  54517. function StopSoundAction(triggerOptions, sound, condition) {
  54518. var _this = _super.call(this, triggerOptions, condition) || this;
  54519. _this._sound = sound;
  54520. return _this;
  54521. }
  54522. StopSoundAction.prototype._prepare = function () {
  54523. };
  54524. StopSoundAction.prototype.execute = function () {
  54525. if (this._sound !== undefined)
  54526. this._sound.stop();
  54527. };
  54528. StopSoundAction.prototype.serialize = function (parent) {
  54529. return _super.prototype._serialize.call(this, {
  54530. name: "StopSoundAction",
  54531. properties: [{ name: "sound", value: this._sound.name }]
  54532. }, parent);
  54533. };
  54534. return StopSoundAction;
  54535. }(BABYLON.Action));
  54536. BABYLON.StopSoundAction = StopSoundAction;
  54537. })(BABYLON || (BABYLON = {}));
  54538. //# sourceMappingURL=babylon.directActions.js.map
  54539. var BABYLON;
  54540. (function (BABYLON) {
  54541. var SpriteManager = /** @class */ (function () {
  54542. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54543. if (epsilon === void 0) { epsilon = 0.01; }
  54544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54545. this.name = name;
  54546. this.sprites = new Array();
  54547. this.renderingGroupId = 0;
  54548. this.layerMask = 0x0FFFFFFF;
  54549. this.fogEnabled = true;
  54550. this.isPickable = false;
  54551. /**
  54552. * An event triggered when the manager is disposed.
  54553. */
  54554. this.onDisposeObservable = new BABYLON.Observable();
  54555. this._vertexBuffers = {};
  54556. this._capacity = capacity;
  54557. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54558. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54559. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54560. if (cellSize.width && cellSize.height) {
  54561. this.cellWidth = cellSize.width;
  54562. this.cellHeight = cellSize.height;
  54563. }
  54564. else if (cellSize !== undefined) {
  54565. this.cellWidth = cellSize;
  54566. this.cellHeight = cellSize;
  54567. }
  54568. else {
  54569. return;
  54570. }
  54571. this._epsilon = epsilon;
  54572. this._scene = scene;
  54573. this._scene.spriteManagers.push(this);
  54574. var indices = [];
  54575. var index = 0;
  54576. for (var count = 0; count < capacity; count++) {
  54577. indices.push(index);
  54578. indices.push(index + 1);
  54579. indices.push(index + 2);
  54580. indices.push(index);
  54581. indices.push(index + 2);
  54582. indices.push(index + 3);
  54583. index += 4;
  54584. }
  54585. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54586. // VBO
  54587. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54588. this._vertexData = new Float32Array(capacity * 16 * 4);
  54589. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54590. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54591. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54592. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54593. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54594. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54595. this._vertexBuffers["options"] = options;
  54596. this._vertexBuffers["cellInfo"] = cellInfo;
  54597. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54598. // Effects
  54599. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54600. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54601. }
  54602. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54603. set: function (callback) {
  54604. if (this._onDisposeObserver) {
  54605. this.onDisposeObservable.remove(this._onDisposeObserver);
  54606. }
  54607. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54608. },
  54609. enumerable: true,
  54610. configurable: true
  54611. });
  54612. Object.defineProperty(SpriteManager.prototype, "texture", {
  54613. get: function () {
  54614. return this._spriteTexture;
  54615. },
  54616. set: function (value) {
  54617. this._spriteTexture = value;
  54618. },
  54619. enumerable: true,
  54620. configurable: true
  54621. });
  54622. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54623. var arrayOffset = index * 16;
  54624. if (offsetX === 0)
  54625. offsetX = this._epsilon;
  54626. else if (offsetX === 1)
  54627. offsetX = 1 - this._epsilon;
  54628. if (offsetY === 0)
  54629. offsetY = this._epsilon;
  54630. else if (offsetY === 1)
  54631. offsetY = 1 - this._epsilon;
  54632. this._vertexData[arrayOffset] = sprite.position.x;
  54633. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54634. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54635. this._vertexData[arrayOffset + 3] = sprite.angle;
  54636. this._vertexData[arrayOffset + 4] = sprite.width;
  54637. this._vertexData[arrayOffset + 5] = sprite.height;
  54638. this._vertexData[arrayOffset + 6] = offsetX;
  54639. this._vertexData[arrayOffset + 7] = offsetY;
  54640. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54641. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54642. var offset = (sprite.cellIndex / rowSize) >> 0;
  54643. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54644. this._vertexData[arrayOffset + 11] = offset;
  54645. // Color
  54646. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54647. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54648. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54649. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54650. };
  54651. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54652. var count = Math.min(this._capacity, this.sprites.length);
  54653. var min = BABYLON.Vector3.Zero();
  54654. var max = BABYLON.Vector3.Zero();
  54655. var distance = Number.MAX_VALUE;
  54656. var currentSprite = null;
  54657. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54658. var cameraView = camera.getViewMatrix();
  54659. for (var index = 0; index < count; index++) {
  54660. var sprite = this.sprites[index];
  54661. if (!sprite) {
  54662. continue;
  54663. }
  54664. if (predicate) {
  54665. if (!predicate(sprite)) {
  54666. continue;
  54667. }
  54668. }
  54669. else if (!sprite.isPickable) {
  54670. continue;
  54671. }
  54672. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54673. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54674. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54675. if (ray.intersectsBoxMinMax(min, max)) {
  54676. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54677. if (distance > currentDistance) {
  54678. distance = currentDistance;
  54679. currentSprite = sprite;
  54680. if (fastCheck) {
  54681. break;
  54682. }
  54683. }
  54684. }
  54685. }
  54686. if (currentSprite) {
  54687. var result = new BABYLON.PickingInfo();
  54688. result.hit = true;
  54689. result.pickedSprite = currentSprite;
  54690. result.distance = distance;
  54691. return result;
  54692. }
  54693. return null;
  54694. };
  54695. SpriteManager.prototype.render = function () {
  54696. // Check
  54697. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54698. return;
  54699. var engine = this._scene.getEngine();
  54700. var baseSize = this._spriteTexture.getBaseSize();
  54701. // Sprites
  54702. var deltaTime = engine.getDeltaTime();
  54703. var max = Math.min(this._capacity, this.sprites.length);
  54704. var rowSize = baseSize.width / this.cellWidth;
  54705. var offset = 0;
  54706. for (var index = 0; index < max; index++) {
  54707. var sprite = this.sprites[index];
  54708. if (!sprite) {
  54709. continue;
  54710. }
  54711. sprite._animate(deltaTime);
  54712. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54713. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54714. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54715. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54716. }
  54717. this._buffer.update(this._vertexData);
  54718. // Render
  54719. var effect = this._effectBase;
  54720. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54721. effect = this._effectFog;
  54722. }
  54723. engine.enableEffect(effect);
  54724. var viewMatrix = this._scene.getViewMatrix();
  54725. effect.setTexture("diffuseSampler", this._spriteTexture);
  54726. effect.setMatrix("view", viewMatrix);
  54727. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54728. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54729. // Fog
  54730. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54731. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54732. effect.setColor3("vFogColor", this._scene.fogColor);
  54733. }
  54734. // VBOs
  54735. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54736. // Draw order
  54737. engine.setDepthFunctionToLessOrEqual();
  54738. effect.setBool("alphaTest", true);
  54739. engine.setColorWrite(false);
  54740. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54741. engine.setColorWrite(true);
  54742. effect.setBool("alphaTest", false);
  54743. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54744. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54745. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54746. };
  54747. SpriteManager.prototype.dispose = function () {
  54748. if (this._buffer) {
  54749. this._buffer.dispose();
  54750. this._buffer = null;
  54751. }
  54752. if (this._indexBuffer) {
  54753. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54754. this._indexBuffer = null;
  54755. }
  54756. if (this._spriteTexture) {
  54757. this._spriteTexture.dispose();
  54758. this._spriteTexture = null;
  54759. }
  54760. // Remove from scene
  54761. var index = this._scene.spriteManagers.indexOf(this);
  54762. this._scene.spriteManagers.splice(index, 1);
  54763. // Callback
  54764. this.onDisposeObservable.notifyObservers(this);
  54765. this.onDisposeObservable.clear();
  54766. };
  54767. return SpriteManager;
  54768. }());
  54769. BABYLON.SpriteManager = SpriteManager;
  54770. })(BABYLON || (BABYLON = {}));
  54771. //# sourceMappingURL=babylon.spriteManager.js.map
  54772. var BABYLON;
  54773. (function (BABYLON) {
  54774. var Sprite = /** @class */ (function () {
  54775. function Sprite(name, manager) {
  54776. this.name = name;
  54777. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54778. this.width = 1.0;
  54779. this.height = 1.0;
  54780. this.angle = 0;
  54781. this.cellIndex = 0;
  54782. this.invertU = 0;
  54783. this.invertV = 0;
  54784. this.animations = new Array();
  54785. this.isPickable = false;
  54786. this._animationStarted = false;
  54787. this._loopAnimation = false;
  54788. this._fromIndex = 0;
  54789. this._toIndex = 0;
  54790. this._delay = 0;
  54791. this._direction = 1;
  54792. this._time = 0;
  54793. this._manager = manager;
  54794. this._manager.sprites.push(this);
  54795. this.position = BABYLON.Vector3.Zero();
  54796. }
  54797. Object.defineProperty(Sprite.prototype, "size", {
  54798. get: function () {
  54799. return this.width;
  54800. },
  54801. set: function (value) {
  54802. this.width = value;
  54803. this.height = value;
  54804. },
  54805. enumerable: true,
  54806. configurable: true
  54807. });
  54808. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54809. this._fromIndex = from;
  54810. this._toIndex = to;
  54811. this._loopAnimation = loop;
  54812. this._delay = delay;
  54813. this._animationStarted = true;
  54814. this._direction = from < to ? 1 : -1;
  54815. this.cellIndex = from;
  54816. this._time = 0;
  54817. this._onAnimationEnd = onAnimationEnd;
  54818. };
  54819. Sprite.prototype.stopAnimation = function () {
  54820. this._animationStarted = false;
  54821. };
  54822. Sprite.prototype._animate = function (deltaTime) {
  54823. if (!this._animationStarted)
  54824. return;
  54825. this._time += deltaTime;
  54826. if (this._time > this._delay) {
  54827. this._time = this._time % this._delay;
  54828. this.cellIndex += this._direction;
  54829. if (this.cellIndex > this._toIndex) {
  54830. if (this._loopAnimation) {
  54831. this.cellIndex = this._fromIndex;
  54832. }
  54833. else {
  54834. this.cellIndex = this._toIndex;
  54835. this._animationStarted = false;
  54836. if (this._onAnimationEnd) {
  54837. this._onAnimationEnd();
  54838. }
  54839. if (this.disposeWhenFinishedAnimating) {
  54840. this.dispose();
  54841. }
  54842. }
  54843. }
  54844. }
  54845. };
  54846. Sprite.prototype.dispose = function () {
  54847. for (var i = 0; i < this._manager.sprites.length; i++) {
  54848. if (this._manager.sprites[i] == this) {
  54849. this._manager.sprites.splice(i, 1);
  54850. }
  54851. }
  54852. };
  54853. return Sprite;
  54854. }());
  54855. BABYLON.Sprite = Sprite;
  54856. })(BABYLON || (BABYLON = {}));
  54857. //# sourceMappingURL=babylon.sprite.js.map
  54858. var BABYLON;
  54859. (function (BABYLON) {
  54860. var IntersectionInfo = /** @class */ (function () {
  54861. function IntersectionInfo(bu, bv, distance) {
  54862. this.bu = bu;
  54863. this.bv = bv;
  54864. this.distance = distance;
  54865. this.faceId = 0;
  54866. this.subMeshId = 0;
  54867. }
  54868. return IntersectionInfo;
  54869. }());
  54870. BABYLON.IntersectionInfo = IntersectionInfo;
  54871. /**
  54872. * Information about the result of picking within a scene
  54873. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54874. */
  54875. var PickingInfo = /** @class */ (function () {
  54876. function PickingInfo() {
  54877. /**
  54878. * If the pick collided with an object
  54879. */
  54880. this.hit = false;
  54881. /**
  54882. * Distance away where the pick collided
  54883. */
  54884. this.distance = 0;
  54885. /**
  54886. * The location of pick collision
  54887. */
  54888. this.pickedPoint = null;
  54889. /**
  54890. * The mesh corrisponding the the pick collision
  54891. */
  54892. this.pickedMesh = null;
  54893. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54894. this.bu = 0;
  54895. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54896. this.bv = 0;
  54897. /** The id of the face on the mesh that was picked */
  54898. this.faceId = -1;
  54899. /** Id of the the submesh that was picked */
  54900. this.subMeshId = 0;
  54901. /** If a sprite was picked, this will be the sprite the pick collided with */
  54902. this.pickedSprite = null;
  54903. /**
  54904. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54905. */
  54906. this.originMesh = null;
  54907. /**
  54908. * The ray that was used to perform the picking.
  54909. */
  54910. this.ray = null;
  54911. }
  54912. /**
  54913. * Gets the normal corrispodning to the face the pick collided with
  54914. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54915. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54916. * @returns The normal corrispodning to the face the pick collided with
  54917. */
  54918. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54919. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54920. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54921. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54922. return null;
  54923. }
  54924. var indices = this.pickedMesh.getIndices();
  54925. if (!indices) {
  54926. return null;
  54927. }
  54928. var result;
  54929. if (useVerticesNormals) {
  54930. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54931. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54932. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54933. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54934. normal0 = normal0.scale(this.bu);
  54935. normal1 = normal1.scale(this.bv);
  54936. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54937. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54938. }
  54939. else {
  54940. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54941. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54942. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54943. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54944. var p1p2 = vertex1.subtract(vertex2);
  54945. var p3p2 = vertex3.subtract(vertex2);
  54946. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54947. }
  54948. if (useWorldCoordinates) {
  54949. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54950. }
  54951. return BABYLON.Vector3.Normalize(result);
  54952. };
  54953. /**
  54954. * Gets the texture coordinates of where the pick occured
  54955. * @returns the vector containing the coordnates of the texture
  54956. */
  54957. PickingInfo.prototype.getTextureCoordinates = function () {
  54958. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54959. return null;
  54960. }
  54961. var indices = this.pickedMesh.getIndices();
  54962. if (!indices) {
  54963. return null;
  54964. }
  54965. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54966. if (!uvs) {
  54967. return null;
  54968. }
  54969. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54970. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54971. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54972. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54973. uv1 = uv1.scale(this.bu);
  54974. uv2 = uv2.scale(this.bv);
  54975. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54976. };
  54977. return PickingInfo;
  54978. }());
  54979. BABYLON.PickingInfo = PickingInfo;
  54980. })(BABYLON || (BABYLON = {}));
  54981. //# sourceMappingURL=babylon.pickingInfo.js.map
  54982. var BABYLON;
  54983. (function (BABYLON) {
  54984. var Ray = /** @class */ (function () {
  54985. function Ray(origin, direction, length) {
  54986. if (length === void 0) { length = Number.MAX_VALUE; }
  54987. this.origin = origin;
  54988. this.direction = direction;
  54989. this.length = length;
  54990. }
  54991. // Methods
  54992. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54993. var d = 0.0;
  54994. var maxValue = Number.MAX_VALUE;
  54995. var inv;
  54996. var min;
  54997. var max;
  54998. var temp;
  54999. if (Math.abs(this.direction.x) < 0.0000001) {
  55000. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55001. return false;
  55002. }
  55003. }
  55004. else {
  55005. inv = 1.0 / this.direction.x;
  55006. min = (minimum.x - this.origin.x) * inv;
  55007. max = (maximum.x - this.origin.x) * inv;
  55008. if (max === -Infinity) {
  55009. max = Infinity;
  55010. }
  55011. if (min > max) {
  55012. temp = min;
  55013. min = max;
  55014. max = temp;
  55015. }
  55016. d = Math.max(min, d);
  55017. maxValue = Math.min(max, maxValue);
  55018. if (d > maxValue) {
  55019. return false;
  55020. }
  55021. }
  55022. if (Math.abs(this.direction.y) < 0.0000001) {
  55023. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55024. return false;
  55025. }
  55026. }
  55027. else {
  55028. inv = 1.0 / this.direction.y;
  55029. min = (minimum.y - this.origin.y) * inv;
  55030. max = (maximum.y - this.origin.y) * inv;
  55031. if (max === -Infinity) {
  55032. max = Infinity;
  55033. }
  55034. if (min > max) {
  55035. temp = min;
  55036. min = max;
  55037. max = temp;
  55038. }
  55039. d = Math.max(min, d);
  55040. maxValue = Math.min(max, maxValue);
  55041. if (d > maxValue) {
  55042. return false;
  55043. }
  55044. }
  55045. if (Math.abs(this.direction.z) < 0.0000001) {
  55046. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55047. return false;
  55048. }
  55049. }
  55050. else {
  55051. inv = 1.0 / this.direction.z;
  55052. min = (minimum.z - this.origin.z) * inv;
  55053. max = (maximum.z - this.origin.z) * inv;
  55054. if (max === -Infinity) {
  55055. max = Infinity;
  55056. }
  55057. if (min > max) {
  55058. temp = min;
  55059. min = max;
  55060. max = temp;
  55061. }
  55062. d = Math.max(min, d);
  55063. maxValue = Math.min(max, maxValue);
  55064. if (d > maxValue) {
  55065. return false;
  55066. }
  55067. }
  55068. return true;
  55069. };
  55070. Ray.prototype.intersectsBox = function (box) {
  55071. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55072. };
  55073. Ray.prototype.intersectsSphere = function (sphere) {
  55074. var x = sphere.center.x - this.origin.x;
  55075. var y = sphere.center.y - this.origin.y;
  55076. var z = sphere.center.z - this.origin.z;
  55077. var pyth = (x * x) + (y * y) + (z * z);
  55078. var rr = sphere.radius * sphere.radius;
  55079. if (pyth <= rr) {
  55080. return true;
  55081. }
  55082. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55083. if (dot < 0.0) {
  55084. return false;
  55085. }
  55086. var temp = pyth - (dot * dot);
  55087. return temp <= rr;
  55088. };
  55089. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55090. if (!this._edge1) {
  55091. this._edge1 = BABYLON.Vector3.Zero();
  55092. this._edge2 = BABYLON.Vector3.Zero();
  55093. this._pvec = BABYLON.Vector3.Zero();
  55094. this._tvec = BABYLON.Vector3.Zero();
  55095. this._qvec = BABYLON.Vector3.Zero();
  55096. }
  55097. vertex1.subtractToRef(vertex0, this._edge1);
  55098. vertex2.subtractToRef(vertex0, this._edge2);
  55099. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55100. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55101. if (det === 0) {
  55102. return null;
  55103. }
  55104. var invdet = 1 / det;
  55105. this.origin.subtractToRef(vertex0, this._tvec);
  55106. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55107. if (bu < 0 || bu > 1.0) {
  55108. return null;
  55109. }
  55110. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55111. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55112. if (bv < 0 || bu + bv > 1.0) {
  55113. return null;
  55114. }
  55115. //check if the distance is longer than the predefined length.
  55116. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55117. if (distance > this.length) {
  55118. return null;
  55119. }
  55120. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55121. };
  55122. Ray.prototype.intersectsPlane = function (plane) {
  55123. var distance;
  55124. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55125. if (Math.abs(result1) < 9.99999997475243E-07) {
  55126. return null;
  55127. }
  55128. else {
  55129. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55130. distance = (-plane.d - result2) / result1;
  55131. if (distance < 0.0) {
  55132. if (distance < -9.99999997475243E-07) {
  55133. return null;
  55134. }
  55135. else {
  55136. return 0;
  55137. }
  55138. }
  55139. return distance;
  55140. }
  55141. };
  55142. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55143. var tm = BABYLON.Tmp.Matrix[0];
  55144. mesh.getWorldMatrix().invertToRef(tm);
  55145. if (this._tmpRay) {
  55146. Ray.TransformToRef(this, tm, this._tmpRay);
  55147. }
  55148. else {
  55149. this._tmpRay = Ray.Transform(this, tm);
  55150. }
  55151. return mesh.intersects(this._tmpRay, fastCheck);
  55152. };
  55153. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55154. if (results) {
  55155. results.length = 0;
  55156. }
  55157. else {
  55158. results = [];
  55159. }
  55160. for (var i = 0; i < meshes.length; i++) {
  55161. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55162. if (pickInfo.hit) {
  55163. results.push(pickInfo);
  55164. }
  55165. }
  55166. results.sort(this._comparePickingInfo);
  55167. return results;
  55168. };
  55169. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55170. if (pickingInfoA.distance < pickingInfoB.distance) {
  55171. return -1;
  55172. }
  55173. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55174. return 1;
  55175. }
  55176. else {
  55177. return 0;
  55178. }
  55179. };
  55180. /**
  55181. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55182. * @param sega the first point of the segment to test the intersection against
  55183. * @param segb the second point of the segment to test the intersection against
  55184. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55185. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55186. */
  55187. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55188. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55189. var u = segb.subtract(sega);
  55190. var v = rsegb.subtract(this.origin);
  55191. var w = sega.subtract(this.origin);
  55192. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55193. var b = BABYLON.Vector3.Dot(u, v);
  55194. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55195. var d = BABYLON.Vector3.Dot(u, w);
  55196. var e = BABYLON.Vector3.Dot(v, w);
  55197. var D = a * c - b * b; // always >= 0
  55198. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55199. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55200. // compute the line parameters of the two closest points
  55201. if (D < Ray.smallnum) { // the lines are almost parallel
  55202. sN = 0.0; // force using point P0 on segment S1
  55203. sD = 1.0; // to prevent possible division by 0.0 later
  55204. tN = e;
  55205. tD = c;
  55206. }
  55207. else { // get the closest points on the infinite lines
  55208. sN = (b * e - c * d);
  55209. tN = (a * e - b * d);
  55210. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55211. sN = 0.0;
  55212. tN = e;
  55213. tD = c;
  55214. }
  55215. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55216. sN = sD;
  55217. tN = e + b;
  55218. tD = c;
  55219. }
  55220. }
  55221. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55222. tN = 0.0;
  55223. // recompute sc for this edge
  55224. if (-d < 0.0) {
  55225. sN = 0.0;
  55226. }
  55227. else if (-d > a)
  55228. sN = sD;
  55229. else {
  55230. sN = -d;
  55231. sD = a;
  55232. }
  55233. }
  55234. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55235. tN = tD;
  55236. // recompute sc for this edge
  55237. if ((-d + b) < 0.0) {
  55238. sN = 0;
  55239. }
  55240. else if ((-d + b) > a) {
  55241. sN = sD;
  55242. }
  55243. else {
  55244. sN = (-d + b);
  55245. sD = a;
  55246. }
  55247. }
  55248. // finally do the division to get sc and tc
  55249. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55250. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55251. // get the difference of the two closest points
  55252. var qtc = v.multiplyByFloats(tc, tc, tc);
  55253. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55254. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55255. if (isIntersected) {
  55256. return qtc.length();
  55257. }
  55258. return -1;
  55259. };
  55260. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55261. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55262. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55263. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55264. this.direction.normalize();
  55265. return this;
  55266. };
  55267. // Statics
  55268. Ray.Zero = function () {
  55269. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55270. };
  55271. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55272. var result = Ray.Zero();
  55273. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55274. };
  55275. /**
  55276. * 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
  55277. * transformed to the given world matrix.
  55278. * @param origin The origin point
  55279. * @param end The end point
  55280. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55281. */
  55282. Ray.CreateNewFromTo = function (origin, end, world) {
  55283. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55284. var direction = end.subtract(origin);
  55285. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55286. direction.normalize();
  55287. return Ray.Transform(new Ray(origin, direction, length), world);
  55288. };
  55289. Ray.Transform = function (ray, matrix) {
  55290. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55291. Ray.TransformToRef(ray, matrix, result);
  55292. return result;
  55293. };
  55294. Ray.TransformToRef = function (ray, matrix, result) {
  55295. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55296. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55297. result.length = ray.length;
  55298. var dir = result.direction;
  55299. var len = dir.length();
  55300. if (!(len === 0 || len === 1)) {
  55301. var num = 1.0 / len;
  55302. dir.x *= num;
  55303. dir.y *= num;
  55304. dir.z *= num;
  55305. result.length *= len;
  55306. }
  55307. };
  55308. Ray.smallnum = 0.00000001;
  55309. Ray.rayl = 10e8;
  55310. return Ray;
  55311. }());
  55312. BABYLON.Ray = Ray;
  55313. })(BABYLON || (BABYLON = {}));
  55314. //# sourceMappingURL=babylon.ray.js.map
  55315. var BABYLON;
  55316. (function (BABYLON) {
  55317. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55318. if (boxMin.x > sphereCenter.x + sphereRadius)
  55319. return false;
  55320. if (sphereCenter.x - sphereRadius > boxMax.x)
  55321. return false;
  55322. if (boxMin.y > sphereCenter.y + sphereRadius)
  55323. return false;
  55324. if (sphereCenter.y - sphereRadius > boxMax.y)
  55325. return false;
  55326. if (boxMin.z > sphereCenter.z + sphereRadius)
  55327. return false;
  55328. if (sphereCenter.z - sphereRadius > boxMax.z)
  55329. return false;
  55330. return true;
  55331. };
  55332. var getLowestRoot = (function () {
  55333. var result = { root: 0, found: false };
  55334. return function (a, b, c, maxR) {
  55335. result.root = 0;
  55336. result.found = false;
  55337. var determinant = b * b - 4.0 * a * c;
  55338. if (determinant < 0)
  55339. return result;
  55340. var sqrtD = Math.sqrt(determinant);
  55341. var r1 = (-b - sqrtD) / (2.0 * a);
  55342. var r2 = (-b + sqrtD) / (2.0 * a);
  55343. if (r1 > r2) {
  55344. var temp = r2;
  55345. r2 = r1;
  55346. r1 = temp;
  55347. }
  55348. if (r1 > 0 && r1 < maxR) {
  55349. result.root = r1;
  55350. result.found = true;
  55351. return result;
  55352. }
  55353. if (r2 > 0 && r2 < maxR) {
  55354. result.root = r2;
  55355. result.found = true;
  55356. return result;
  55357. }
  55358. return result;
  55359. };
  55360. })();
  55361. var Collider = /** @class */ (function () {
  55362. function Collider() {
  55363. this._collisionPoint = BABYLON.Vector3.Zero();
  55364. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55365. this._tempVector = BABYLON.Vector3.Zero();
  55366. this._tempVector2 = BABYLON.Vector3.Zero();
  55367. this._tempVector3 = BABYLON.Vector3.Zero();
  55368. this._tempVector4 = BABYLON.Vector3.Zero();
  55369. this._edge = BABYLON.Vector3.Zero();
  55370. this._baseToVertex = BABYLON.Vector3.Zero();
  55371. this._destinationPoint = BABYLON.Vector3.Zero();
  55372. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55373. this._displacementVector = BABYLON.Vector3.Zero();
  55374. this._radius = BABYLON.Vector3.One();
  55375. this._retry = 0;
  55376. this._basePointWorld = BABYLON.Vector3.Zero();
  55377. this._velocityWorld = BABYLON.Vector3.Zero();
  55378. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55379. this._collisionMask = -1;
  55380. }
  55381. Object.defineProperty(Collider.prototype, "collisionMask", {
  55382. get: function () {
  55383. return this._collisionMask;
  55384. },
  55385. set: function (mask) {
  55386. this._collisionMask = !isNaN(mask) ? mask : -1;
  55387. },
  55388. enumerable: true,
  55389. configurable: true
  55390. });
  55391. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55392. /**
  55393. * Gets the plane normal used to compute the sliding response (in local space)
  55394. */
  55395. get: function () {
  55396. return this._slidePlaneNormal;
  55397. },
  55398. enumerable: true,
  55399. configurable: true
  55400. });
  55401. // Methods
  55402. Collider.prototype._initialize = function (source, dir, e) {
  55403. this._velocity = dir;
  55404. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55405. this._basePoint = source;
  55406. source.multiplyToRef(this._radius, this._basePointWorld);
  55407. dir.multiplyToRef(this._radius, this._velocityWorld);
  55408. this._velocityWorldLength = this._velocityWorld.length();
  55409. this._epsilon = e;
  55410. this.collisionFound = false;
  55411. };
  55412. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55413. pa.subtractToRef(point, this._tempVector);
  55414. pb.subtractToRef(point, this._tempVector2);
  55415. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55416. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55417. if (d < 0)
  55418. return false;
  55419. pc.subtractToRef(point, this._tempVector3);
  55420. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55421. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55422. if (d < 0)
  55423. return false;
  55424. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55425. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55426. return d >= 0;
  55427. };
  55428. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55429. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55430. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55431. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55432. return false;
  55433. }
  55434. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55435. return false;
  55436. return true;
  55437. };
  55438. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55439. var t0;
  55440. var embeddedInPlane = false;
  55441. //defensive programming, actually not needed.
  55442. if (!trianglePlaneArray) {
  55443. trianglePlaneArray = [];
  55444. }
  55445. if (!trianglePlaneArray[faceIndex]) {
  55446. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55447. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55448. }
  55449. var trianglePlane = trianglePlaneArray[faceIndex];
  55450. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55451. return;
  55452. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55453. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55454. if (normalDotVelocity == 0) {
  55455. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55456. return;
  55457. embeddedInPlane = true;
  55458. t0 = 0;
  55459. }
  55460. else {
  55461. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55462. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55463. if (t0 > t1) {
  55464. var temp = t1;
  55465. t1 = t0;
  55466. t0 = temp;
  55467. }
  55468. if (t0 > 1.0 || t1 < 0.0)
  55469. return;
  55470. if (t0 < 0)
  55471. t0 = 0;
  55472. if (t0 > 1.0)
  55473. t0 = 1.0;
  55474. }
  55475. this._collisionPoint.copyFromFloats(0, 0, 0);
  55476. var found = false;
  55477. var t = 1.0;
  55478. if (!embeddedInPlane) {
  55479. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55480. this._velocity.scaleToRef(t0, this._tempVector);
  55481. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55482. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55483. found = true;
  55484. t = t0;
  55485. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55486. }
  55487. }
  55488. if (!found) {
  55489. var velocitySquaredLength = this._velocity.lengthSquared();
  55490. var a = velocitySquaredLength;
  55491. this._basePoint.subtractToRef(p1, this._tempVector);
  55492. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55493. var c = this._tempVector.lengthSquared() - 1.0;
  55494. var lowestRoot = getLowestRoot(a, b, c, t);
  55495. if (lowestRoot.found) {
  55496. t = lowestRoot.root;
  55497. found = true;
  55498. this._collisionPoint.copyFrom(p1);
  55499. }
  55500. this._basePoint.subtractToRef(p2, this._tempVector);
  55501. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55502. c = this._tempVector.lengthSquared() - 1.0;
  55503. lowestRoot = getLowestRoot(a, b, c, t);
  55504. if (lowestRoot.found) {
  55505. t = lowestRoot.root;
  55506. found = true;
  55507. this._collisionPoint.copyFrom(p2);
  55508. }
  55509. this._basePoint.subtractToRef(p3, this._tempVector);
  55510. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55511. c = this._tempVector.lengthSquared() - 1.0;
  55512. lowestRoot = getLowestRoot(a, b, c, t);
  55513. if (lowestRoot.found) {
  55514. t = lowestRoot.root;
  55515. found = true;
  55516. this._collisionPoint.copyFrom(p3);
  55517. }
  55518. p2.subtractToRef(p1, this._edge);
  55519. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55520. var edgeSquaredLength = this._edge.lengthSquared();
  55521. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55522. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55523. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55524. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55525. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55526. lowestRoot = getLowestRoot(a, b, c, t);
  55527. if (lowestRoot.found) {
  55528. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55529. if (f >= 0.0 && f <= 1.0) {
  55530. t = lowestRoot.root;
  55531. found = true;
  55532. this._edge.scaleInPlace(f);
  55533. p1.addToRef(this._edge, this._collisionPoint);
  55534. }
  55535. }
  55536. p3.subtractToRef(p2, this._edge);
  55537. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55538. edgeSquaredLength = this._edge.lengthSquared();
  55539. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55540. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55541. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55542. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55543. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55544. lowestRoot = getLowestRoot(a, b, c, t);
  55545. if (lowestRoot.found) {
  55546. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55547. if (f >= 0.0 && f <= 1.0) {
  55548. t = lowestRoot.root;
  55549. found = true;
  55550. this._edge.scaleInPlace(f);
  55551. p2.addToRef(this._edge, this._collisionPoint);
  55552. }
  55553. }
  55554. p1.subtractToRef(p3, this._edge);
  55555. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55556. edgeSquaredLength = this._edge.lengthSquared();
  55557. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55558. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55559. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55560. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55561. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55562. lowestRoot = getLowestRoot(a, b, c, t);
  55563. if (lowestRoot.found) {
  55564. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55565. if (f >= 0.0 && f <= 1.0) {
  55566. t = lowestRoot.root;
  55567. found = true;
  55568. this._edge.scaleInPlace(f);
  55569. p3.addToRef(this._edge, this._collisionPoint);
  55570. }
  55571. }
  55572. }
  55573. if (found) {
  55574. var distToCollision = t * this._velocity.length();
  55575. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55576. if (!this.intersectionPoint) {
  55577. this.intersectionPoint = this._collisionPoint.clone();
  55578. }
  55579. else {
  55580. this.intersectionPoint.copyFrom(this._collisionPoint);
  55581. }
  55582. this._nearestDistance = distToCollision;
  55583. this.collisionFound = true;
  55584. }
  55585. }
  55586. };
  55587. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55588. for (var i = indexStart; i < indexEnd; i += 3) {
  55589. var p1 = pts[indices[i] - decal];
  55590. var p2 = pts[indices[i + 1] - decal];
  55591. var p3 = pts[indices[i + 2] - decal];
  55592. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55593. }
  55594. };
  55595. Collider.prototype._getResponse = function (pos, vel) {
  55596. pos.addToRef(vel, this._destinationPoint);
  55597. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55598. this._basePoint.addToRef(vel, pos);
  55599. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55600. this._slidePlaneNormal.normalize();
  55601. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55602. pos.addInPlace(this._displacementVector);
  55603. this.intersectionPoint.addInPlace(this._displacementVector);
  55604. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55605. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55606. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55607. };
  55608. return Collider;
  55609. }());
  55610. BABYLON.Collider = Collider;
  55611. })(BABYLON || (BABYLON = {}));
  55612. //# sourceMappingURL=babylon.collider.js.map
  55613. var BABYLON;
  55614. (function (BABYLON) {
  55615. //WebWorker code will be inserted to this variable.
  55616. BABYLON.CollisionWorker = "";
  55617. /** Defines supported task for worker process */
  55618. var WorkerTaskType;
  55619. (function (WorkerTaskType) {
  55620. /** Initialization */
  55621. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55622. /** Update of geometry */
  55623. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55624. /** Evaluate collision */
  55625. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55626. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55627. /** Defines kind of replies returned by worker */
  55628. var WorkerReplyType;
  55629. (function (WorkerReplyType) {
  55630. /** Success */
  55631. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55632. /** Unkown error */
  55633. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55634. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55635. var CollisionCoordinatorWorker = /** @class */ (function () {
  55636. function CollisionCoordinatorWorker() {
  55637. var _this = this;
  55638. this._scaledPosition = BABYLON.Vector3.Zero();
  55639. this._scaledVelocity = BABYLON.Vector3.Zero();
  55640. this.onMeshUpdated = function (transformNode) {
  55641. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55642. };
  55643. this.onGeometryUpdated = function (geometry) {
  55644. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55645. };
  55646. this._afterRender = function () {
  55647. if (!_this._init)
  55648. return;
  55649. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55650. return;
  55651. }
  55652. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55653. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55654. if (_this._runningUpdated > 4) {
  55655. return;
  55656. }
  55657. ++_this._runningUpdated;
  55658. var payload = {
  55659. updatedMeshes: _this._addUpdateMeshesList,
  55660. updatedGeometries: _this._addUpdateGeometriesList,
  55661. removedGeometries: _this._toRemoveGeometryArray,
  55662. removedMeshes: _this._toRemoveMeshesArray
  55663. };
  55664. var message = {
  55665. payload: payload,
  55666. taskType: WorkerTaskType.UPDATE
  55667. };
  55668. var serializable = [];
  55669. for (var id in payload.updatedGeometries) {
  55670. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55671. //prepare transferables
  55672. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55673. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55674. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55675. }
  55676. }
  55677. _this._worker.postMessage(message, serializable);
  55678. _this._addUpdateMeshesList = {};
  55679. _this._addUpdateGeometriesList = {};
  55680. _this._toRemoveGeometryArray = [];
  55681. _this._toRemoveMeshesArray = [];
  55682. };
  55683. this._onMessageFromWorker = function (e) {
  55684. var returnData = e.data;
  55685. if (returnData.error != WorkerReplyType.SUCCESS) {
  55686. //TODO what errors can be returned from the worker?
  55687. BABYLON.Tools.Warn("error returned from worker!");
  55688. return;
  55689. }
  55690. switch (returnData.taskType) {
  55691. case WorkerTaskType.INIT:
  55692. _this._init = true;
  55693. //Update the worked with ALL of the scene's current state
  55694. _this._scene.meshes.forEach(function (mesh) {
  55695. _this.onMeshAdded(mesh);
  55696. });
  55697. _this._scene.getGeometries().forEach(function (geometry) {
  55698. _this.onGeometryAdded(geometry);
  55699. });
  55700. break;
  55701. case WorkerTaskType.UPDATE:
  55702. _this._runningUpdated--;
  55703. break;
  55704. case WorkerTaskType.COLLIDE:
  55705. var returnPayload = returnData.payload;
  55706. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55707. return;
  55708. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55709. if (callback) {
  55710. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55711. if (mesh) {
  55712. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55713. }
  55714. }
  55715. //cleanup
  55716. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55717. break;
  55718. }
  55719. };
  55720. this._collisionsCallbackArray = [];
  55721. this._init = false;
  55722. this._runningUpdated = 0;
  55723. this._addUpdateMeshesList = {};
  55724. this._addUpdateGeometriesList = {};
  55725. this._toRemoveGeometryArray = [];
  55726. this._toRemoveMeshesArray = [];
  55727. }
  55728. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55729. if (!this._init)
  55730. return;
  55731. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55732. return;
  55733. position.divideToRef(collider._radius, this._scaledPosition);
  55734. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55735. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55736. var payload = {
  55737. collider: {
  55738. position: this._scaledPosition.asArray(),
  55739. velocity: this._scaledVelocity.asArray(),
  55740. radius: collider._radius.asArray()
  55741. },
  55742. collisionId: collisionIndex,
  55743. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55744. maximumRetry: maximumRetry
  55745. };
  55746. var message = {
  55747. payload: payload,
  55748. taskType: WorkerTaskType.COLLIDE
  55749. };
  55750. this._worker.postMessage(message);
  55751. };
  55752. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55753. this._scene = scene;
  55754. this._scene.registerAfterRender(this._afterRender);
  55755. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55756. this._worker = new Worker(workerUrl);
  55757. this._worker.onmessage = this._onMessageFromWorker;
  55758. var message = {
  55759. payload: {},
  55760. taskType: WorkerTaskType.INIT
  55761. };
  55762. this._worker.postMessage(message);
  55763. };
  55764. CollisionCoordinatorWorker.prototype.destroy = function () {
  55765. this._scene.unregisterAfterRender(this._afterRender);
  55766. this._worker.terminate();
  55767. };
  55768. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55769. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55770. this.onMeshUpdated(mesh);
  55771. };
  55772. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55773. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55774. };
  55775. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55776. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55777. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55778. this.onGeometryUpdated(geometry);
  55779. };
  55780. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55781. this._toRemoveGeometryArray.push(geometry.id);
  55782. };
  55783. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55784. var submeshes = [];
  55785. if (mesh.subMeshes) {
  55786. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55787. var boundingInfo = sm.getBoundingInfo();
  55788. return {
  55789. position: idx,
  55790. verticesStart: sm.verticesStart,
  55791. verticesCount: sm.verticesCount,
  55792. indexStart: sm.indexStart,
  55793. indexCount: sm.indexCount,
  55794. hasMaterial: !!sm.getMaterial(),
  55795. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55796. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55797. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55798. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55799. };
  55800. });
  55801. }
  55802. var geometryId = null;
  55803. if (mesh instanceof BABYLON.Mesh) {
  55804. var geometry = mesh.geometry;
  55805. geometryId = geometry ? geometry.id : null;
  55806. }
  55807. else if (mesh instanceof BABYLON.InstancedMesh) {
  55808. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55809. geometryId = geometry ? geometry.id : null;
  55810. }
  55811. var boundingInfo = mesh.getBoundingInfo();
  55812. return {
  55813. uniqueId: mesh.uniqueId,
  55814. id: mesh.id,
  55815. name: mesh.name,
  55816. geometryId: geometryId,
  55817. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55818. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55819. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55820. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55821. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55822. subMeshes: submeshes,
  55823. checkCollisions: mesh.checkCollisions
  55824. };
  55825. };
  55826. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55827. return {
  55828. id: geometry.id,
  55829. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55830. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55831. indices: new Uint32Array(geometry.getIndices() || []),
  55832. };
  55833. };
  55834. return CollisionCoordinatorWorker;
  55835. }());
  55836. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55837. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55838. function CollisionCoordinatorLegacy() {
  55839. this._scaledPosition = BABYLON.Vector3.Zero();
  55840. this._scaledVelocity = BABYLON.Vector3.Zero();
  55841. this._finalPosition = BABYLON.Vector3.Zero();
  55842. }
  55843. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55844. position.divideToRef(collider._radius, this._scaledPosition);
  55845. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55846. collider.collidedMesh = null;
  55847. collider._retry = 0;
  55848. collider._initialVelocity = this._scaledVelocity;
  55849. collider._initialPosition = this._scaledPosition;
  55850. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55851. this._finalPosition.multiplyInPlace(collider._radius);
  55852. //run the callback
  55853. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55854. };
  55855. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55856. this._scene = scene;
  55857. };
  55858. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55859. //Legacy need no destruction method.
  55860. };
  55861. //No update in legacy mode
  55862. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55863. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55864. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55865. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55866. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55867. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55868. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55869. if (excludedMesh === void 0) { excludedMesh = null; }
  55870. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55871. if (collider._retry >= maximumRetry) {
  55872. finalPosition.copyFrom(position);
  55873. return;
  55874. }
  55875. // Check if this is a mesh else camera or -1
  55876. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55877. collider._initialize(position, velocity, closeDistance);
  55878. // Check all meshes
  55879. for (var index = 0; index < this._scene.meshes.length; index++) {
  55880. var mesh = this._scene.meshes[index];
  55881. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55882. mesh._checkCollision(collider);
  55883. }
  55884. }
  55885. if (!collider.collisionFound) {
  55886. position.addToRef(velocity, finalPosition);
  55887. return;
  55888. }
  55889. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55890. collider._getResponse(position, velocity);
  55891. }
  55892. if (velocity.length() <= closeDistance) {
  55893. finalPosition.copyFrom(position);
  55894. return;
  55895. }
  55896. collider._retry++;
  55897. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55898. };
  55899. return CollisionCoordinatorLegacy;
  55900. }());
  55901. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55902. })(BABYLON || (BABYLON = {}));
  55903. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55904. var BABYLON;
  55905. (function (BABYLON) {
  55906. /**
  55907. * A particle represents one of the element emitted by a particle system.
  55908. * This is mainly define by its coordinates, direction, velocity and age.
  55909. */
  55910. var Particle = /** @class */ (function () {
  55911. /**
  55912. * Creates a new instance Particle
  55913. * @param particleSystem the particle system the particle belongs to
  55914. */
  55915. function Particle(
  55916. /**
  55917. * particleSystem the particle system the particle belongs to.
  55918. */
  55919. particleSystem) {
  55920. this.particleSystem = particleSystem;
  55921. /**
  55922. * The world position of the particle in the scene.
  55923. */
  55924. this.position = BABYLON.Vector3.Zero();
  55925. /**
  55926. * The world direction of the particle in the scene.
  55927. */
  55928. this.direction = BABYLON.Vector3.Zero();
  55929. /**
  55930. * The color of the particle.
  55931. */
  55932. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55933. /**
  55934. * The color change of the particle per step.
  55935. */
  55936. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55937. /**
  55938. * Defines how long will the life of the particle be.
  55939. */
  55940. this.lifeTime = 1.0;
  55941. /**
  55942. * The current age of the particle.
  55943. */
  55944. this.age = 0;
  55945. /**
  55946. * The current size of the particle.
  55947. */
  55948. this.size = 0;
  55949. /**
  55950. * The current angle of the particle.
  55951. */
  55952. this.angle = 0;
  55953. /**
  55954. * Defines how fast is the angle changing.
  55955. */
  55956. this.angularSpeed = 0;
  55957. /**
  55958. * Defines the cell index used by the particle to be rendered from a sprite.
  55959. */
  55960. this.cellIndex = 0;
  55961. this._currentFrameCounter = 0;
  55962. if (!this.particleSystem.isAnimationSheetEnabled) {
  55963. return;
  55964. }
  55965. this.updateCellInfoFromSystem();
  55966. }
  55967. Particle.prototype.updateCellInfoFromSystem = function () {
  55968. this.cellIndex = this.particleSystem.startSpriteCellID;
  55969. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55970. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55971. }
  55972. else {
  55973. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55974. }
  55975. };
  55976. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55977. // (ageOffset / scaledUpdateSpeed) / available cells
  55978. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55979. this._currentFrameCounter += scaledUpdateSpeed;
  55980. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55981. this._currentFrameCounter = 0;
  55982. this.cellIndex++;
  55983. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55984. this.cellIndex = this.particleSystem.endSpriteCellID;
  55985. }
  55986. }
  55987. };
  55988. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55989. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55990. this.cellIndex++;
  55991. this._currentFrameCounter = 0;
  55992. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55993. if (this.particleSystem.spriteCellLoop) {
  55994. this.cellIndex = this.particleSystem.startSpriteCellID;
  55995. }
  55996. else {
  55997. this.cellIndex = this.particleSystem.endSpriteCellID;
  55998. }
  55999. }
  56000. }
  56001. else {
  56002. this._currentFrameCounter++;
  56003. }
  56004. };
  56005. /**
  56006. * Copy the properties of particle to another one.
  56007. * @param other the particle to copy the information to.
  56008. */
  56009. Particle.prototype.copyTo = function (other) {
  56010. other.position.copyFrom(this.position);
  56011. other.direction.copyFrom(this.direction);
  56012. other.color.copyFrom(this.color);
  56013. other.colorStep.copyFrom(this.colorStep);
  56014. other.lifeTime = this.lifeTime;
  56015. other.age = this.age;
  56016. other.size = this.size;
  56017. other.angle = this.angle;
  56018. other.angularSpeed = this.angularSpeed;
  56019. other.particleSystem = this.particleSystem;
  56020. other.cellIndex = this.cellIndex;
  56021. };
  56022. return Particle;
  56023. }());
  56024. BABYLON.Particle = Particle;
  56025. })(BABYLON || (BABYLON = {}));
  56026. //# sourceMappingURL=babylon.particle.js.map
  56027. var BABYLON;
  56028. (function (BABYLON) {
  56029. /**
  56030. * This represents a particle system in Babylon.
  56031. * 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.
  56032. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56033. * @example https://doc.babylonjs.com/babylon101/particles
  56034. */
  56035. var ParticleSystem = /** @class */ (function () {
  56036. /**
  56037. * Instantiates a particle system.
  56038. * 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.
  56039. * @param name The name of the particle system
  56040. * @param capacity The max number of particles alive at the same time
  56041. * @param scene The scene the particle system belongs to
  56042. * @param customEffect a custom effect used to change the way particles are rendered by default
  56043. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56044. * @param epsilon Offset used to render the particles
  56045. */
  56046. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56047. if (customEffect === void 0) { customEffect = null; }
  56048. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56049. if (epsilon === void 0) { epsilon = 0.01; }
  56050. var _this = this;
  56051. /**
  56052. * List of animations used by the particle system.
  56053. */
  56054. this.animations = [];
  56055. /**
  56056. * The rendering group used by the Particle system to chose when to render.
  56057. */
  56058. this.renderingGroupId = 0;
  56059. /**
  56060. * The emitter represents the Mesh or position we are attaching the particle system to.
  56061. */
  56062. this.emitter = null;
  56063. /**
  56064. * The maximum number of particles to emit per frame
  56065. */
  56066. this.emitRate = 10;
  56067. /**
  56068. * If you want to launch only a few particles at once, that can be done, as well.
  56069. */
  56070. this.manualEmitCount = -1;
  56071. /**
  56072. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56073. */
  56074. this.updateSpeed = 0.01;
  56075. /**
  56076. * The amount of time the particle system is running (depends of the overall update speed).
  56077. */
  56078. this.targetStopDuration = 0;
  56079. /**
  56080. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56081. */
  56082. this.disposeOnStop = false;
  56083. /**
  56084. * Minimum power of emitting particles.
  56085. */
  56086. this.minEmitPower = 1;
  56087. /**
  56088. * Maximum power of emitting particles.
  56089. */
  56090. this.maxEmitPower = 1;
  56091. /**
  56092. * Minimum life time of emitting particles.
  56093. */
  56094. this.minLifeTime = 1;
  56095. /**
  56096. * Maximum life time of emitting particles.
  56097. */
  56098. this.maxLifeTime = 1;
  56099. /**
  56100. * Minimum Size of emitting particles.
  56101. */
  56102. this.minSize = 1;
  56103. /**
  56104. * Maximum Size of emitting particles.
  56105. */
  56106. this.maxSize = 1;
  56107. /**
  56108. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56109. */
  56110. this.minAngularSpeed = 0;
  56111. /**
  56112. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56113. */
  56114. this.maxAngularSpeed = 0;
  56115. /**
  56116. * The layer mask we are rendering the particles through.
  56117. */
  56118. this.layerMask = 0x0FFFFFFF;
  56119. /**
  56120. * This can help using your own shader to render the particle system.
  56121. * The according effect will be created
  56122. */
  56123. this.customShader = null;
  56124. /**
  56125. * By default particle system starts as soon as they are created. This prevents the
  56126. * automatic start to happen and let you decide when to start emitting particles.
  56127. */
  56128. this.preventAutoStart = false;
  56129. /**
  56130. * Callback triggered when the particle animation is ending.
  56131. */
  56132. this.onAnimationEnd = null;
  56133. /**
  56134. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56135. */
  56136. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56137. /**
  56138. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56139. * to override the particles.
  56140. */
  56141. this.forceDepthWrite = false;
  56142. /**
  56143. * You can use gravity if you want to give an orientation to your particles.
  56144. */
  56145. this.gravity = BABYLON.Vector3.Zero();
  56146. /**
  56147. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56148. */
  56149. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56150. /**
  56151. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56152. */
  56153. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56154. /**
  56155. * Color the particle will have at the end of its lifetime.
  56156. */
  56157. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56158. /**
  56159. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56160. */
  56161. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56162. /**
  56163. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56164. */
  56165. this.spriteCellLoop = true;
  56166. /**
  56167. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56168. */
  56169. this.spriteCellChangeSpeed = 0;
  56170. /**
  56171. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56172. */
  56173. this.startSpriteCellID = 0;
  56174. /**
  56175. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56176. */
  56177. this.endSpriteCellID = 0;
  56178. /**
  56179. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56180. */
  56181. this.spriteCellWidth = 0;
  56182. /**
  56183. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56184. */
  56185. this.spriteCellHeight = 0;
  56186. /**
  56187. * An event triggered when the system is disposed.
  56188. */
  56189. this.onDisposeObservable = new BABYLON.Observable();
  56190. this._particles = new Array();
  56191. this._stockParticles = new Array();
  56192. this._newPartsExcess = 0;
  56193. this._vertexBuffers = {};
  56194. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56195. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56196. this._scaledDirection = BABYLON.Vector3.Zero();
  56197. this._scaledGravity = BABYLON.Vector3.Zero();
  56198. this._currentRenderId = -1;
  56199. this._started = false;
  56200. this._stopped = false;
  56201. this._actualFrame = 0;
  56202. this._vertexBufferSize = 11;
  56203. // start of sub system methods
  56204. /**
  56205. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56206. * Its lifetime will start back at 0.
  56207. */
  56208. this.recycleParticle = function (particle) {
  56209. var lastParticle = _this._particles.pop();
  56210. if (lastParticle !== particle) {
  56211. lastParticle.copyTo(particle);
  56212. }
  56213. _this._stockParticles.push(lastParticle);
  56214. };
  56215. this._createParticle = function () {
  56216. var particle;
  56217. if (_this._stockParticles.length !== 0) {
  56218. particle = _this._stockParticles.pop();
  56219. particle.age = 0;
  56220. particle.cellIndex = _this.startSpriteCellID;
  56221. }
  56222. else {
  56223. particle = new BABYLON.Particle(_this);
  56224. }
  56225. return particle;
  56226. };
  56227. this._emitFromParticle = function (particle) {
  56228. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56229. return;
  56230. }
  56231. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56232. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56233. subSystem._rootParticleSystem = _this;
  56234. _this.activeSubSystems.push(subSystem);
  56235. subSystem.start();
  56236. };
  56237. this._appendParticleVertexes = null;
  56238. this.id = name;
  56239. this.name = name;
  56240. this._capacity = capacity;
  56241. this._epsilon = epsilon;
  56242. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56243. if (isAnimationSheetEnabled) {
  56244. this._vertexBufferSize = 12;
  56245. }
  56246. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56247. this._customEffect = customEffect;
  56248. scene.particleSystems.push(this);
  56249. this._createIndexBuffer();
  56250. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56251. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56252. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56253. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56254. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56255. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56256. if (this._isAnimationSheetEnabled) {
  56257. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56258. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56259. }
  56260. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56261. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56262. this._vertexBuffers["options"] = options;
  56263. // Default emitter type
  56264. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56265. this.updateFunction = function (particles) {
  56266. for (var index = 0; index < particles.length; index++) {
  56267. var particle = particles[index];
  56268. particle.age += _this._scaledUpdateSpeed;
  56269. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56270. _this._emitFromParticle(particle);
  56271. _this.recycleParticle(particle);
  56272. index--;
  56273. continue;
  56274. }
  56275. else {
  56276. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56277. particle.color.addInPlace(_this._scaledColorStep);
  56278. if (particle.color.a < 0)
  56279. particle.color.a = 0;
  56280. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56281. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56282. particle.position.addInPlace(_this._scaledDirection);
  56283. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56284. particle.direction.addInPlace(_this._scaledGravity);
  56285. if (_this._isAnimationSheetEnabled) {
  56286. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56287. }
  56288. }
  56289. }
  56290. };
  56291. }
  56292. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56293. /**
  56294. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56295. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56296. */
  56297. get: function () {
  56298. if (this.particleEmitterType.direction1) {
  56299. return this.particleEmitterType.direction1;
  56300. }
  56301. return BABYLON.Vector3.Zero();
  56302. },
  56303. set: function (value) {
  56304. if (this.particleEmitterType.direction1) {
  56305. this.particleEmitterType.direction1 = value;
  56306. }
  56307. },
  56308. enumerable: true,
  56309. configurable: true
  56310. });
  56311. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56312. /**
  56313. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56314. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56315. */
  56316. get: function () {
  56317. if (this.particleEmitterType.direction2) {
  56318. return this.particleEmitterType.direction2;
  56319. }
  56320. return BABYLON.Vector3.Zero();
  56321. },
  56322. set: function (value) {
  56323. if (this.particleEmitterType.direction2) {
  56324. this.particleEmitterType.direction2 = value;
  56325. }
  56326. },
  56327. enumerable: true,
  56328. configurable: true
  56329. });
  56330. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56331. /**
  56332. * 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.
  56333. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56334. */
  56335. get: function () {
  56336. if (this.particleEmitterType.minEmitBox) {
  56337. return this.particleEmitterType.minEmitBox;
  56338. }
  56339. return BABYLON.Vector3.Zero();
  56340. },
  56341. set: function (value) {
  56342. if (this.particleEmitterType.minEmitBox) {
  56343. this.particleEmitterType.minEmitBox = value;
  56344. }
  56345. },
  56346. enumerable: true,
  56347. configurable: true
  56348. });
  56349. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56350. /**
  56351. * 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.
  56352. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56353. */
  56354. get: function () {
  56355. if (this.particleEmitterType.maxEmitBox) {
  56356. return this.particleEmitterType.maxEmitBox;
  56357. }
  56358. return BABYLON.Vector3.Zero();
  56359. },
  56360. set: function (value) {
  56361. if (this.particleEmitterType.maxEmitBox) {
  56362. this.particleEmitterType.maxEmitBox = value;
  56363. }
  56364. },
  56365. enumerable: true,
  56366. configurable: true
  56367. });
  56368. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56369. /**
  56370. * Sets a callback that will be triggered when the system is disposed.
  56371. */
  56372. set: function (callback) {
  56373. if (this._onDisposeObserver) {
  56374. this.onDisposeObservable.remove(this._onDisposeObserver);
  56375. }
  56376. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56377. },
  56378. enumerable: true,
  56379. configurable: true
  56380. });
  56381. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56382. /**
  56383. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56384. */
  56385. get: function () {
  56386. return this._isAnimationSheetEnabled;
  56387. },
  56388. enumerable: true,
  56389. configurable: true
  56390. });
  56391. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56392. //end of Sub-emitter
  56393. /**
  56394. * Gets the current list of active particles
  56395. */
  56396. get: function () {
  56397. return this._particles;
  56398. },
  56399. enumerable: true,
  56400. configurable: true
  56401. });
  56402. /**
  56403. * Returns the string "ParticleSystem"
  56404. * @returns a string containing the class name
  56405. */
  56406. ParticleSystem.prototype.getClassName = function () {
  56407. return "ParticleSystem";
  56408. };
  56409. ParticleSystem.prototype._createIndexBuffer = function () {
  56410. var indices = [];
  56411. var index = 0;
  56412. for (var count = 0; count < this._capacity; count++) {
  56413. indices.push(index);
  56414. indices.push(index + 1);
  56415. indices.push(index + 2);
  56416. indices.push(index);
  56417. indices.push(index + 2);
  56418. indices.push(index + 3);
  56419. index += 4;
  56420. }
  56421. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56422. };
  56423. /**
  56424. * Gets the maximum number of particles active at the same time.
  56425. * @returns The max number of active particles.
  56426. */
  56427. ParticleSystem.prototype.getCapacity = function () {
  56428. return this._capacity;
  56429. };
  56430. /**
  56431. * Gets Wether there are still active particles in the system.
  56432. * @returns True if it is alive, otherwise false.
  56433. */
  56434. ParticleSystem.prototype.isAlive = function () {
  56435. return this._alive;
  56436. };
  56437. /**
  56438. * Gets Wether the system has been started.
  56439. * @returns True if it has been started, otherwise false.
  56440. */
  56441. ParticleSystem.prototype.isStarted = function () {
  56442. return this._started;
  56443. };
  56444. /**
  56445. * Starts the particle system and begins to emit.
  56446. */
  56447. ParticleSystem.prototype.start = function () {
  56448. this._started = true;
  56449. this._stopped = false;
  56450. this._actualFrame = 0;
  56451. if (this.subEmitters && this.subEmitters.length != 0) {
  56452. this.activeSubSystems = new Array();
  56453. }
  56454. };
  56455. /**
  56456. * Stops the particle system.
  56457. * @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.
  56458. */
  56459. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56460. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56461. this._stopped = true;
  56462. if (stopSubEmitters) {
  56463. this._stopSubEmitters();
  56464. }
  56465. };
  56466. // animation sheet
  56467. /**
  56468. * Remove all active particles
  56469. */
  56470. ParticleSystem.prototype.reset = function () {
  56471. this._stockParticles = [];
  56472. this._particles = [];
  56473. };
  56474. /**
  56475. * @hidden (for internal use only)
  56476. */
  56477. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56478. var offset = index * this._vertexBufferSize;
  56479. this._vertexData[offset] = particle.position.x;
  56480. this._vertexData[offset + 1] = particle.position.y;
  56481. this._vertexData[offset + 2] = particle.position.z;
  56482. this._vertexData[offset + 3] = particle.color.r;
  56483. this._vertexData[offset + 4] = particle.color.g;
  56484. this._vertexData[offset + 5] = particle.color.b;
  56485. this._vertexData[offset + 6] = particle.color.a;
  56486. this._vertexData[offset + 7] = particle.angle;
  56487. this._vertexData[offset + 8] = particle.size;
  56488. this._vertexData[offset + 9] = offsetX;
  56489. this._vertexData[offset + 10] = offsetY;
  56490. };
  56491. /**
  56492. * @hidden (for internal use only)
  56493. */
  56494. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56495. if (offsetX === 0)
  56496. offsetX = this._epsilon;
  56497. else if (offsetX === 1)
  56498. offsetX = 1 - this._epsilon;
  56499. if (offsetY === 0)
  56500. offsetY = this._epsilon;
  56501. else if (offsetY === 1)
  56502. offsetY = 1 - this._epsilon;
  56503. var offset = index * this._vertexBufferSize;
  56504. this._vertexData[offset] = particle.position.x;
  56505. this._vertexData[offset + 1] = particle.position.y;
  56506. this._vertexData[offset + 2] = particle.position.z;
  56507. this._vertexData[offset + 3] = particle.color.r;
  56508. this._vertexData[offset + 4] = particle.color.g;
  56509. this._vertexData[offset + 5] = particle.color.b;
  56510. this._vertexData[offset + 6] = particle.color.a;
  56511. this._vertexData[offset + 7] = particle.angle;
  56512. this._vertexData[offset + 8] = particle.size;
  56513. this._vertexData[offset + 9] = offsetX;
  56514. this._vertexData[offset + 10] = offsetY;
  56515. this._vertexData[offset + 11] = particle.cellIndex;
  56516. };
  56517. ParticleSystem.prototype._stopSubEmitters = function () {
  56518. if (!this.activeSubSystems) {
  56519. return;
  56520. }
  56521. this.activeSubSystems.forEach(function (subSystem) {
  56522. subSystem.stop(true);
  56523. });
  56524. this.activeSubSystems = new Array();
  56525. };
  56526. ParticleSystem.prototype._removeFromRoot = function () {
  56527. if (!this._rootParticleSystem) {
  56528. return;
  56529. }
  56530. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56531. if (index !== -1) {
  56532. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56533. }
  56534. };
  56535. // end of sub system methods
  56536. ParticleSystem.prototype._update = function (newParticles) {
  56537. // Update current
  56538. this._alive = this._particles.length > 0;
  56539. this.updateFunction(this._particles);
  56540. // Add new ones
  56541. var worldMatrix;
  56542. if (this.emitter.position) {
  56543. var emitterMesh = this.emitter;
  56544. worldMatrix = emitterMesh.getWorldMatrix();
  56545. }
  56546. else {
  56547. var emitterPosition = this.emitter;
  56548. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56549. }
  56550. var particle;
  56551. for (var index = 0; index < newParticles; index++) {
  56552. if (this._particles.length === this._capacity) {
  56553. break;
  56554. }
  56555. particle = this._createParticle();
  56556. this._particles.push(particle);
  56557. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56558. if (this.startPositionFunction) {
  56559. this.startPositionFunction(worldMatrix, particle.position, particle);
  56560. }
  56561. else {
  56562. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56563. }
  56564. if (this.startDirectionFunction) {
  56565. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56566. }
  56567. else {
  56568. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56569. }
  56570. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56571. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56572. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56573. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56574. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56575. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56576. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56577. }
  56578. };
  56579. ParticleSystem.prototype._getEffect = function () {
  56580. if (this._customEffect) {
  56581. return this._customEffect;
  56582. }
  56583. ;
  56584. var defines = [];
  56585. if (this._scene.clipPlane) {
  56586. defines.push("#define CLIPPLANE");
  56587. }
  56588. if (this._isAnimationSheetEnabled) {
  56589. defines.push("#define ANIMATESHEET");
  56590. }
  56591. // Effect
  56592. var join = defines.join("\n");
  56593. if (this._cachedDefines !== join) {
  56594. this._cachedDefines = join;
  56595. var attributesNamesOrOptions;
  56596. var effectCreationOption;
  56597. if (this._isAnimationSheetEnabled) {
  56598. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56599. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56600. }
  56601. else {
  56602. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56603. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56604. }
  56605. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56606. }
  56607. return this._effect;
  56608. };
  56609. /**
  56610. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56611. */
  56612. ParticleSystem.prototype.animate = function () {
  56613. if (!this._started)
  56614. return;
  56615. var effect = this._getEffect();
  56616. // Check
  56617. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56618. return;
  56619. if (this._currentRenderId === this._scene.getRenderId()) {
  56620. return;
  56621. }
  56622. this._currentRenderId = this._scene.getRenderId();
  56623. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56624. // determine the number of particles we need to create
  56625. var newParticles;
  56626. if (this.manualEmitCount > -1) {
  56627. newParticles = this.manualEmitCount;
  56628. this._newPartsExcess = 0;
  56629. this.manualEmitCount = 0;
  56630. }
  56631. else {
  56632. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56633. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56634. }
  56635. if (this._newPartsExcess > 1.0) {
  56636. newParticles += this._newPartsExcess >> 0;
  56637. this._newPartsExcess -= this._newPartsExcess >> 0;
  56638. }
  56639. this._alive = false;
  56640. if (!this._stopped) {
  56641. this._actualFrame += this._scaledUpdateSpeed;
  56642. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56643. this.stop();
  56644. }
  56645. else {
  56646. newParticles = 0;
  56647. }
  56648. this._update(newParticles);
  56649. // Stopped?
  56650. if (this._stopped) {
  56651. if (!this._alive) {
  56652. this._started = false;
  56653. if (this.onAnimationEnd) {
  56654. this.onAnimationEnd();
  56655. }
  56656. if (this.disposeOnStop) {
  56657. this._scene._toBeDisposed.push(this);
  56658. }
  56659. }
  56660. }
  56661. // Animation sheet
  56662. if (this._isAnimationSheetEnabled) {
  56663. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56664. }
  56665. else {
  56666. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56667. }
  56668. // Update VBO
  56669. var offset = 0;
  56670. for (var index = 0; index < this._particles.length; index++) {
  56671. var particle = this._particles[index];
  56672. this._appendParticleVertexes(offset, particle);
  56673. offset += 4;
  56674. }
  56675. if (this._vertexBuffer) {
  56676. this._vertexBuffer.update(this._vertexData);
  56677. }
  56678. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56679. this.stop();
  56680. }
  56681. };
  56682. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56683. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56684. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56685. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56686. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56687. };
  56688. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56689. this._appendParticleVertex(offset++, particle, 0, 0);
  56690. this._appendParticleVertex(offset++, particle, 1, 0);
  56691. this._appendParticleVertex(offset++, particle, 1, 1);
  56692. this._appendParticleVertex(offset++, particle, 0, 1);
  56693. };
  56694. /**
  56695. * Rebuilds the particle system.
  56696. */
  56697. ParticleSystem.prototype.rebuild = function () {
  56698. this._createIndexBuffer();
  56699. if (this._vertexBuffer) {
  56700. this._vertexBuffer._rebuild();
  56701. }
  56702. };
  56703. /**
  56704. * Is this system ready to be used/rendered
  56705. * @return true if the system is ready
  56706. */
  56707. ParticleSystem.prototype.isReady = function () {
  56708. var effect = this._getEffect();
  56709. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56710. return false;
  56711. }
  56712. return true;
  56713. };
  56714. /**
  56715. * Renders the particle system in its current state.
  56716. * @returns the current number of particles
  56717. */
  56718. ParticleSystem.prototype.render = function () {
  56719. var effect = this._getEffect();
  56720. // Check
  56721. if (!this.isReady() || !this._particles.length) {
  56722. return 0;
  56723. }
  56724. var engine = this._scene.getEngine();
  56725. // Render
  56726. engine.enableEffect(effect);
  56727. engine.setState(false);
  56728. var viewMatrix = this._scene.getViewMatrix();
  56729. effect.setTexture("diffuseSampler", this.particleTexture);
  56730. effect.setMatrix("view", viewMatrix);
  56731. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56732. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56733. var baseSize = this.particleTexture.getBaseSize();
  56734. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56735. }
  56736. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56737. if (this._scene.clipPlane) {
  56738. var clipPlane = this._scene.clipPlane;
  56739. var invView = viewMatrix.clone();
  56740. invView.invert();
  56741. effect.setMatrix("invView", invView);
  56742. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56743. }
  56744. // VBOs
  56745. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56746. // Draw order
  56747. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56748. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56749. }
  56750. else {
  56751. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56752. }
  56753. if (this.forceDepthWrite) {
  56754. engine.setDepthWrite(true);
  56755. }
  56756. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56757. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56758. return this._particles.length;
  56759. };
  56760. /**
  56761. * Disposes the particle system and free the associated resources
  56762. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56763. */
  56764. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56765. if (disposeTexture === void 0) { disposeTexture = true; }
  56766. if (this._vertexBuffer) {
  56767. this._vertexBuffer.dispose();
  56768. this._vertexBuffer = null;
  56769. }
  56770. if (this._indexBuffer) {
  56771. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56772. this._indexBuffer = null;
  56773. }
  56774. if (disposeTexture && this.particleTexture) {
  56775. this.particleTexture.dispose();
  56776. this.particleTexture = null;
  56777. }
  56778. this._removeFromRoot();
  56779. // Remove from scene
  56780. var index = this._scene.particleSystems.indexOf(this);
  56781. if (index > -1) {
  56782. this._scene.particleSystems.splice(index, 1);
  56783. }
  56784. // Callback
  56785. this.onDisposeObservable.notifyObservers(this);
  56786. this.onDisposeObservable.clear();
  56787. };
  56788. /**
  56789. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56790. * @param radius The radius of the sphere to emit from
  56791. * @returns the emitter
  56792. */
  56793. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56794. if (radius === void 0) { radius = 1; }
  56795. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56796. this.particleEmitterType = particleEmitter;
  56797. return particleEmitter;
  56798. };
  56799. /**
  56800. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56801. * @param radius The radius of the sphere to emit from
  56802. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56803. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56804. * @returns the emitter
  56805. */
  56806. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56807. if (radius === void 0) { radius = 1; }
  56808. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56809. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56810. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56811. this.particleEmitterType = particleEmitter;
  56812. return particleEmitter;
  56813. };
  56814. /**
  56815. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56816. * @param radius The radius of the cone to emit from
  56817. * @param angle The base angle of the cone
  56818. * @returns the emitter
  56819. */
  56820. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56821. if (radius === void 0) { radius = 1; }
  56822. if (angle === void 0) { angle = Math.PI / 4; }
  56823. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56824. this.particleEmitterType = particleEmitter;
  56825. return particleEmitter;
  56826. };
  56827. // 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.
  56828. /**
  56829. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56830. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56831. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56832. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56833. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56834. * @returns the emitter
  56835. */
  56836. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56837. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56838. this.particleEmitterType = particleEmitter;
  56839. this.direction1 = direction1;
  56840. this.direction2 = direction2;
  56841. this.minEmitBox = minEmitBox;
  56842. this.maxEmitBox = maxEmitBox;
  56843. return particleEmitter;
  56844. };
  56845. // Clone
  56846. /**
  56847. * Clones the particle system.
  56848. * @param name The name of the cloned object
  56849. * @param newEmitter The new emitter to use
  56850. * @returns the cloned particle system
  56851. */
  56852. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56853. var custom = null;
  56854. var program = null;
  56855. if (this.customShader != null) {
  56856. program = this.customShader;
  56857. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56858. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56859. }
  56860. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56861. result.customShader = program;
  56862. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56863. if (newEmitter === undefined) {
  56864. newEmitter = this.emitter;
  56865. }
  56866. result.emitter = newEmitter;
  56867. if (this.particleTexture) {
  56868. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56869. }
  56870. if (!this.preventAutoStart) {
  56871. result.start();
  56872. }
  56873. return result;
  56874. };
  56875. /**
  56876. * Serializes the particle system to a JSON object.
  56877. * @returns the JSON object
  56878. */
  56879. ParticleSystem.prototype.serialize = function () {
  56880. var serializationObject = {};
  56881. serializationObject.name = this.name;
  56882. serializationObject.id = this.id;
  56883. // Emitter
  56884. if (this.emitter.position) {
  56885. var emitterMesh = this.emitter;
  56886. serializationObject.emitterId = emitterMesh.id;
  56887. }
  56888. else {
  56889. var emitterPosition = this.emitter;
  56890. serializationObject.emitter = emitterPosition.asArray();
  56891. }
  56892. serializationObject.capacity = this.getCapacity();
  56893. if (this.particleTexture) {
  56894. serializationObject.textureName = this.particleTexture.name;
  56895. }
  56896. // Animations
  56897. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56898. // Particle system
  56899. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56900. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56901. serializationObject.minSize = this.minSize;
  56902. serializationObject.maxSize = this.maxSize;
  56903. serializationObject.minEmitPower = this.minEmitPower;
  56904. serializationObject.maxEmitPower = this.maxEmitPower;
  56905. serializationObject.minLifeTime = this.minLifeTime;
  56906. serializationObject.maxLifeTime = this.maxLifeTime;
  56907. serializationObject.emitRate = this.emitRate;
  56908. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56909. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56910. serializationObject.gravity = this.gravity.asArray();
  56911. serializationObject.direction1 = this.direction1.asArray();
  56912. serializationObject.direction2 = this.direction2.asArray();
  56913. serializationObject.color1 = this.color1.asArray();
  56914. serializationObject.color2 = this.color2.asArray();
  56915. serializationObject.colorDead = this.colorDead.asArray();
  56916. serializationObject.updateSpeed = this.updateSpeed;
  56917. serializationObject.targetStopDuration = this.targetStopDuration;
  56918. serializationObject.textureMask = this.textureMask.asArray();
  56919. serializationObject.blendMode = this.blendMode;
  56920. serializationObject.customShader = this.customShader;
  56921. serializationObject.preventAutoStart = this.preventAutoStart;
  56922. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56923. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56924. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56925. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56926. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56927. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56928. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56929. // Emitter
  56930. if (this.particleEmitterType) {
  56931. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56932. }
  56933. return serializationObject;
  56934. };
  56935. /**
  56936. * Parses a JSON object to create a particle system.
  56937. * @param parsedParticleSystem The JSON object to parse
  56938. * @param scene The scene to create the particle system in
  56939. * @param rootUrl The root url to use to load external dependencies like texture
  56940. * @returns the Parsed particle system
  56941. */
  56942. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56943. var name = parsedParticleSystem.name;
  56944. var custom = null;
  56945. var program = null;
  56946. if (parsedParticleSystem.customShader) {
  56947. program = parsedParticleSystem.customShader;
  56948. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56949. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56950. }
  56951. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56952. particleSystem.customShader = program;
  56953. if (parsedParticleSystem.id) {
  56954. particleSystem.id = parsedParticleSystem.id;
  56955. }
  56956. // Auto start
  56957. if (parsedParticleSystem.preventAutoStart) {
  56958. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56959. }
  56960. // Texture
  56961. if (parsedParticleSystem.textureName) {
  56962. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56963. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56964. }
  56965. // Emitter
  56966. if (parsedParticleSystem.emitterId) {
  56967. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56968. }
  56969. else {
  56970. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56971. }
  56972. // Animations
  56973. if (parsedParticleSystem.animations) {
  56974. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56975. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56976. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56977. }
  56978. }
  56979. if (parsedParticleSystem.autoAnimate) {
  56980. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56981. }
  56982. // Particle system
  56983. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56984. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56985. particleSystem.minSize = parsedParticleSystem.minSize;
  56986. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56987. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56988. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56989. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56990. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56991. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56992. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56993. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56994. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56995. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56996. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56997. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56998. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56999. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57000. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57001. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57002. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57003. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57004. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57005. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57006. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57007. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57008. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57009. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57010. if (!particleSystem.preventAutoStart) {
  57011. particleSystem.start();
  57012. }
  57013. return particleSystem;
  57014. };
  57015. /**
  57016. * Source color is added to the destination color without alpha affecting the result.
  57017. */
  57018. ParticleSystem.BLENDMODE_ONEONE = 0;
  57019. /**
  57020. * Blend current color and particle color using particle’s alpha.
  57021. */
  57022. ParticleSystem.BLENDMODE_STANDARD = 1;
  57023. return ParticleSystem;
  57024. }());
  57025. BABYLON.ParticleSystem = ParticleSystem;
  57026. })(BABYLON || (BABYLON = {}));
  57027. //# sourceMappingURL=babylon.particleSystem.js.map
  57028. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57029. var BABYLON;
  57030. (function (BABYLON) {
  57031. /**
  57032. * Particle emitter emitting particles from the inside of a box.
  57033. * It emits the particles randomly between 2 given directions.
  57034. */
  57035. var BoxParticleEmitter = /** @class */ (function () {
  57036. /**
  57037. * Creates a new instance BoxParticleEmitter
  57038. */
  57039. function BoxParticleEmitter() {
  57040. /**
  57041. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57042. */
  57043. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57044. /**
  57045. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57046. */
  57047. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57048. /**
  57049. * 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.
  57050. */
  57051. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57052. /**
  57053. * 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.
  57054. */
  57055. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57056. }
  57057. /**
  57058. * Called by the particle System when the direction is computed for the created particle.
  57059. * @param emitPower is the power of the particle (speed)
  57060. * @param worldMatrix is the world matrix of the particle system
  57061. * @param directionToUpdate is the direction vector to update with the result
  57062. * @param particle is the particle we are computed the direction for
  57063. */
  57064. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57065. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57066. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57067. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57068. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57069. };
  57070. /**
  57071. * Called by the particle System when the position is computed for the created particle.
  57072. * @param worldMatrix is the world matrix of the particle system
  57073. * @param positionToUpdate is the position vector to update with the result
  57074. * @param particle is the particle we are computed the position for
  57075. */
  57076. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57077. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57078. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57079. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57080. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57081. };
  57082. /**
  57083. * Clones the current emitter and returns a copy of it
  57084. * @returns the new emitter
  57085. */
  57086. BoxParticleEmitter.prototype.clone = function () {
  57087. var newOne = new BoxParticleEmitter();
  57088. BABYLON.Tools.DeepCopy(this, newOne);
  57089. return newOne;
  57090. };
  57091. /**
  57092. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57093. * @param effect defines the update shader
  57094. */
  57095. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57096. effect.setVector3("direction1", this.direction1);
  57097. effect.setVector3("direction2", this.direction2);
  57098. effect.setVector3("minEmitBox", this.minEmitBox);
  57099. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57100. };
  57101. /**
  57102. * Returns a string to use to update the GPU particles update shader
  57103. * @returns a string containng the defines string
  57104. */
  57105. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57106. return "#define BOXEMITTER";
  57107. };
  57108. /**
  57109. * Returns the string "BoxEmitter"
  57110. * @returns a string containing the class name
  57111. */
  57112. BoxParticleEmitter.prototype.getClassName = function () {
  57113. return "BoxEmitter";
  57114. };
  57115. /**
  57116. * Serializes the particle system to a JSON object.
  57117. * @returns the JSON object
  57118. */
  57119. BoxParticleEmitter.prototype.serialize = function () {
  57120. var serializationObject = {};
  57121. serializationObject.type = this.getClassName();
  57122. serializationObject.direction1 = this.direction1.asArray();
  57123. serializationObject.direction2 = this.direction2.asArray();
  57124. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57125. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57126. return serializationObject;
  57127. };
  57128. /**
  57129. * Parse properties from a JSON object
  57130. * @param serializationObject defines the JSON object
  57131. */
  57132. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57133. this.direction1.copyFrom(serializationObject.direction1);
  57134. this.direction2.copyFrom(serializationObject.direction2);
  57135. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57136. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57137. };
  57138. return BoxParticleEmitter;
  57139. }());
  57140. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57141. })(BABYLON || (BABYLON = {}));
  57142. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57143. var BABYLON;
  57144. (function (BABYLON) {
  57145. /**
  57146. * Particle emitter emitting particles from the inside of a cone.
  57147. * It emits the particles alongside the cone volume from the base to the particle.
  57148. * The emission direction might be randomized.
  57149. */
  57150. var ConeParticleEmitter = /** @class */ (function () {
  57151. /**
  57152. * Creates a new instance ConeParticleEmitter
  57153. * @param radius the radius of the emission cone (1 by default)
  57154. * @param angles the cone base angle (PI by default)
  57155. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57156. */
  57157. function ConeParticleEmitter(radius,
  57158. /**
  57159. * The radius of the emission cone.
  57160. */
  57161. angle,
  57162. /**
  57163. * The cone base angle.
  57164. */
  57165. directionRandomizer) {
  57166. if (radius === void 0) { radius = 1; }
  57167. if (angle === void 0) { angle = Math.PI; }
  57168. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57169. this.angle = angle;
  57170. this.directionRandomizer = directionRandomizer;
  57171. this.radius = radius;
  57172. }
  57173. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57174. /**
  57175. * Gets the radius of the emission cone.
  57176. */
  57177. get: function () {
  57178. return this._radius;
  57179. },
  57180. /**
  57181. * Sets the radius of the emission cone.
  57182. */
  57183. set: function (value) {
  57184. this._radius = value;
  57185. if (this.angle !== 0) {
  57186. this._height = value / Math.tan(this.angle / 2);
  57187. }
  57188. else {
  57189. this._height = 1;
  57190. }
  57191. },
  57192. enumerable: true,
  57193. configurable: true
  57194. });
  57195. /**
  57196. * Called by the particle System when the direction is computed for the created particle.
  57197. * @param emitPower is the power of the particle (speed)
  57198. * @param worldMatrix is the world matrix of the particle system
  57199. * @param directionToUpdate is the direction vector to update with the result
  57200. * @param particle is the particle we are computed the direction for
  57201. */
  57202. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57203. if (this.angle === 0) {
  57204. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57205. }
  57206. else {
  57207. // measure the direction Vector from the emitter to the particle.
  57208. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57209. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57210. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57211. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57212. direction.x += randX;
  57213. direction.y += randY;
  57214. direction.z += randZ;
  57215. direction.normalize();
  57216. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57217. }
  57218. };
  57219. /**
  57220. * Called by the particle System when the position is computed for the created particle.
  57221. * @param worldMatrix is the world matrix of the particle system
  57222. * @param positionToUpdate is the position vector to update with the result
  57223. * @param particle is the particle we are computed the position for
  57224. */
  57225. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57226. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57227. var h = BABYLON.Scalar.RandomRange(0, 1);
  57228. // Better distribution in a cone at normal angles.
  57229. h = 1 - h * h;
  57230. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57231. radius = radius * h;
  57232. var randX = radius * Math.sin(s);
  57233. var randZ = radius * Math.cos(s);
  57234. var randY = h * this._height;
  57235. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57236. };
  57237. /**
  57238. * Clones the current emitter and returns a copy of it
  57239. * @returns the new emitter
  57240. */
  57241. ConeParticleEmitter.prototype.clone = function () {
  57242. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57243. BABYLON.Tools.DeepCopy(this, newOne);
  57244. return newOne;
  57245. };
  57246. /**
  57247. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57248. * @param effect defines the update shader
  57249. */
  57250. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57251. effect.setFloat("radius", this.radius);
  57252. effect.setFloat("coneAngle", this.angle);
  57253. effect.setFloat("height", this._height);
  57254. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57255. };
  57256. /**
  57257. * Returns a string to use to update the GPU particles update shader
  57258. * @returns a string containng the defines string
  57259. */
  57260. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57261. return "#define CONEEMITTER";
  57262. };
  57263. /**
  57264. * Returns the string "BoxEmitter"
  57265. * @returns a string containing the class name
  57266. */
  57267. ConeParticleEmitter.prototype.getClassName = function () {
  57268. return "ConeEmitter";
  57269. };
  57270. /**
  57271. * Serializes the particle system to a JSON object.
  57272. * @returns the JSON object
  57273. */
  57274. ConeParticleEmitter.prototype.serialize = function () {
  57275. var serializationObject = {};
  57276. serializationObject.type = this.getClassName();
  57277. serializationObject.radius = this.radius;
  57278. serializationObject.angle = this.angle;
  57279. serializationObject.directionRandomizer = this.directionRandomizer;
  57280. return serializationObject;
  57281. };
  57282. /**
  57283. * Parse properties from a JSON object
  57284. * @param serializationObject defines the JSON object
  57285. */
  57286. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57287. this.radius = serializationObject.radius;
  57288. this.angle = serializationObject.angle;
  57289. this.directionRandomizer = serializationObject.directionRandomizer;
  57290. };
  57291. return ConeParticleEmitter;
  57292. }());
  57293. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57294. })(BABYLON || (BABYLON = {}));
  57295. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57296. var BABYLON;
  57297. (function (BABYLON) {
  57298. /**
  57299. * Particle emitter emitting particles from the inside of a sphere.
  57300. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57301. */
  57302. var SphereParticleEmitter = /** @class */ (function () {
  57303. /**
  57304. * Creates a new instance SphereParticleEmitter
  57305. * @param radius the radius of the emission sphere (1 by default)
  57306. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57307. */
  57308. function SphereParticleEmitter(
  57309. /**
  57310. * The radius of the emission sphere.
  57311. */
  57312. radius,
  57313. /**
  57314. * How much to randomize the particle direction [0-1].
  57315. */
  57316. directionRandomizer) {
  57317. if (radius === void 0) { radius = 1; }
  57318. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57319. this.radius = radius;
  57320. this.directionRandomizer = directionRandomizer;
  57321. }
  57322. /**
  57323. * Called by the particle System when the direction is computed for the created particle.
  57324. * @param emitPower is the power of the particle (speed)
  57325. * @param worldMatrix is the world matrix of the particle system
  57326. * @param directionToUpdate is the direction vector to update with the result
  57327. * @param particle is the particle we are computed the direction for
  57328. */
  57329. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57330. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57331. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57332. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57333. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57334. direction.x += randX;
  57335. direction.y += randY;
  57336. direction.z += randZ;
  57337. direction.normalize();
  57338. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57339. };
  57340. /**
  57341. * Called by the particle System when the position is computed for the created particle.
  57342. * @param worldMatrix is the world matrix of the particle system
  57343. * @param positionToUpdate is the position vector to update with the result
  57344. * @param particle is the particle we are computed the position for
  57345. */
  57346. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57347. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57348. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57349. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57350. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57351. var randY = randRadius * Math.cos(theta);
  57352. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57353. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57354. };
  57355. /**
  57356. * Clones the current emitter and returns a copy of it
  57357. * @returns the new emitter
  57358. */
  57359. SphereParticleEmitter.prototype.clone = function () {
  57360. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57361. BABYLON.Tools.DeepCopy(this, newOne);
  57362. return newOne;
  57363. };
  57364. /**
  57365. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57366. * @param effect defines the update shader
  57367. */
  57368. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57369. effect.setFloat("radius", this.radius);
  57370. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57371. };
  57372. /**
  57373. * Returns a string to use to update the GPU particles update shader
  57374. * @returns a string containng the defines string
  57375. */
  57376. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57377. return "#define SPHEREEMITTER";
  57378. };
  57379. /**
  57380. * Returns the string "SphereParticleEmitter"
  57381. * @returns a string containing the class name
  57382. */
  57383. SphereParticleEmitter.prototype.getClassName = function () {
  57384. return "SphereParticleEmitter";
  57385. };
  57386. /**
  57387. * Serializes the particle system to a JSON object.
  57388. * @returns the JSON object
  57389. */
  57390. SphereParticleEmitter.prototype.serialize = function () {
  57391. var serializationObject = {};
  57392. serializationObject.type = this.getClassName();
  57393. serializationObject.radius = this.radius;
  57394. serializationObject.directionRandomizer = this.directionRandomizer;
  57395. return serializationObject;
  57396. };
  57397. /**
  57398. * Parse properties from a JSON object
  57399. * @param serializationObject defines the JSON object
  57400. */
  57401. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57402. this.radius = serializationObject.radius;
  57403. this.directionRandomizer = serializationObject.directionRandomizer;
  57404. };
  57405. return SphereParticleEmitter;
  57406. }());
  57407. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57408. /**
  57409. * Particle emitter emitting particles from the inside of a sphere.
  57410. * It emits the particles randomly between two vectors.
  57411. */
  57412. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57413. __extends(SphereDirectedParticleEmitter, _super);
  57414. /**
  57415. * Creates a new instance SphereDirectedParticleEmitter
  57416. * @param radius the radius of the emission sphere (1 by default)
  57417. * @param direction1 the min limit of the emission direction (up vector by default)
  57418. * @param direction2 the max limit of the emission direction (up vector by default)
  57419. */
  57420. function SphereDirectedParticleEmitter(radius,
  57421. /**
  57422. * The min limit of the emission direction.
  57423. */
  57424. direction1,
  57425. /**
  57426. * The max limit of the emission direction.
  57427. */
  57428. direction2) {
  57429. if (radius === void 0) { radius = 1; }
  57430. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57431. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57432. var _this = _super.call(this, radius) || this;
  57433. _this.direction1 = direction1;
  57434. _this.direction2 = direction2;
  57435. return _this;
  57436. }
  57437. /**
  57438. * Called by the particle System when the direction is computed for the created particle.
  57439. * @param emitPower is the power of the particle (speed)
  57440. * @param worldMatrix is the world matrix of the particle system
  57441. * @param directionToUpdate is the direction vector to update with the result
  57442. * @param particle is the particle we are computed the direction for
  57443. */
  57444. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57445. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57446. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57447. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57448. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57449. };
  57450. /**
  57451. * Clones the current emitter and returns a copy of it
  57452. * @returns the new emitter
  57453. */
  57454. SphereDirectedParticleEmitter.prototype.clone = function () {
  57455. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57456. BABYLON.Tools.DeepCopy(this, newOne);
  57457. return newOne;
  57458. };
  57459. /**
  57460. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57461. * @param effect defines the update shader
  57462. */
  57463. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57464. effect.setFloat("radius", this.radius);
  57465. effect.setVector3("direction1", this.direction1);
  57466. effect.setVector3("direction2", this.direction2);
  57467. };
  57468. /**
  57469. * Returns a string to use to update the GPU particles update shader
  57470. * @returns a string containng the defines string
  57471. */
  57472. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57473. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57474. };
  57475. /**
  57476. * Returns the string "SphereDirectedParticleEmitter"
  57477. * @returns a string containing the class name
  57478. */
  57479. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57480. return "SphereDirectedParticleEmitter";
  57481. };
  57482. /**
  57483. * Serializes the particle system to a JSON object.
  57484. * @returns the JSON object
  57485. */
  57486. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57487. var serializationObject = _super.prototype.serialize.call(this);
  57488. serializationObject.direction1 = this.direction1.asArray();
  57489. serializationObject.direction2 = this.direction2.asArray();
  57490. return serializationObject;
  57491. };
  57492. /**
  57493. * Parse properties from a JSON object
  57494. * @param serializationObject defines the JSON object
  57495. */
  57496. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57497. _super.prototype.parse.call(this, serializationObject);
  57498. this.direction1.copyFrom(serializationObject.direction1);
  57499. this.direction2.copyFrom(serializationObject.direction2);
  57500. };
  57501. return SphereDirectedParticleEmitter;
  57502. }(SphereParticleEmitter));
  57503. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57504. })(BABYLON || (BABYLON = {}));
  57505. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57506. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57507. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57508. s = arguments[i];
  57509. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57510. t[p] = s[p];
  57511. }
  57512. return t;
  57513. };
  57514. var BABYLON;
  57515. (function (BABYLON) {
  57516. /**
  57517. * This represents a GPU particle system in Babylon
  57518. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57519. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57520. */
  57521. var GPUParticleSystem = /** @class */ (function () {
  57522. /**
  57523. * Instantiates a GPU particle system.
  57524. * 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.
  57525. * @param name The name of the particle system
  57526. * @param capacity The max number of particles alive at the same time
  57527. * @param scene The scene the particle system belongs to
  57528. */
  57529. function GPUParticleSystem(name, options, scene) {
  57530. /**
  57531. * The emitter represents the Mesh or position we are attaching the particle system to.
  57532. */
  57533. this.emitter = null;
  57534. /**
  57535. * The rendering group used by the Particle system to chose when to render.
  57536. */
  57537. this.renderingGroupId = 0;
  57538. /**
  57539. * The layer mask we are rendering the particles through.
  57540. */
  57541. this.layerMask = 0x0FFFFFFF;
  57542. this._targetIndex = 0;
  57543. this._currentRenderId = -1;
  57544. this._started = false;
  57545. this._stopped = false;
  57546. this._timeDelta = 0;
  57547. this._attributesStrideSize = 16;
  57548. this._actualFrame = 0;
  57549. /**
  57550. * List of animations used by the particle system.
  57551. */
  57552. this.animations = [];
  57553. /**
  57554. * An event triggered when the system is disposed.
  57555. */
  57556. this.onDisposeObservable = new BABYLON.Observable();
  57557. /**
  57558. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57559. */
  57560. this.updateSpeed = 0.01;
  57561. /**
  57562. * The amount of time the particle system is running (depends of the overall update speed).
  57563. */
  57564. this.targetStopDuration = 0;
  57565. /**
  57566. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57567. */
  57568. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57569. /**
  57570. * Minimum life time of emitting particles.
  57571. */
  57572. this.minLifeTime = 1;
  57573. /**
  57574. * Maximum life time of emitting particles.
  57575. */
  57576. this.maxLifeTime = 1;
  57577. /**
  57578. * Minimum Size of emitting particles.
  57579. */
  57580. this.minSize = 1;
  57581. /**
  57582. * Maximum Size of emitting particles.
  57583. */
  57584. this.maxSize = 1;
  57585. /**
  57586. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57587. */
  57588. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57589. /**
  57590. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57591. */
  57592. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57593. /**
  57594. * Color the particle will have at the end of its lifetime.
  57595. */
  57596. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57597. /**
  57598. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57599. */
  57600. this.emitRate = 100;
  57601. /**
  57602. * You can use gravity if you want to give an orientation to your particles.
  57603. */
  57604. this.gravity = BABYLON.Vector3.Zero();
  57605. /**
  57606. * Minimum power of emitting particles.
  57607. */
  57608. this.minEmitPower = 1;
  57609. /**
  57610. * Maximum power of emitting particles.
  57611. */
  57612. this.maxEmitPower = 1;
  57613. /**
  57614. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57615. */
  57616. this.minAngularSpeed = 0;
  57617. /**
  57618. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57619. */
  57620. this.maxAngularSpeed = 0;
  57621. /**
  57622. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57623. * to override the particles.
  57624. */
  57625. this.forceDepthWrite = false;
  57626. this.id = name;
  57627. this.name = name;
  57628. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57629. this._engine = this._scene.getEngine();
  57630. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57631. this._capacity = fullOptions.capacity;
  57632. this._activeCount = fullOptions.capacity;
  57633. this._currentActiveCount = 0;
  57634. this._scene.particleSystems.push(this);
  57635. this._updateEffectOptions = {
  57636. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57637. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57638. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57639. "angleRange"],
  57640. uniformBuffersNames: [],
  57641. samplers: ["randomSampler"],
  57642. defines: "",
  57643. fallbacks: null,
  57644. onCompiled: null,
  57645. onError: null,
  57646. indexParameters: null,
  57647. maxSimultaneousLights: 0,
  57648. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57649. };
  57650. // Random data
  57651. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57652. var d = [];
  57653. for (var i = 0; i < maxTextureSize; ++i) {
  57654. d.push(Math.random());
  57655. d.push(Math.random());
  57656. d.push(Math.random());
  57657. d.push(Math.random());
  57658. }
  57659. 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);
  57660. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57661. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57662. this._randomTextureSize = maxTextureSize;
  57663. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57664. }
  57665. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57666. /**
  57667. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57668. */
  57669. get: function () {
  57670. if (!BABYLON.Engine.LastCreatedEngine) {
  57671. return false;
  57672. }
  57673. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57674. },
  57675. enumerable: true,
  57676. configurable: true
  57677. });
  57678. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57679. /**
  57680. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57681. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57682. */
  57683. get: function () {
  57684. if (this.particleEmitterType.direction1) {
  57685. return this.particleEmitterType.direction1;
  57686. }
  57687. return BABYLON.Vector3.Zero();
  57688. },
  57689. set: function (value) {
  57690. if (this.particleEmitterType.direction1) {
  57691. this.particleEmitterType.direction1 = value;
  57692. }
  57693. },
  57694. enumerable: true,
  57695. configurable: true
  57696. });
  57697. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57698. /**
  57699. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57700. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57701. */
  57702. get: function () {
  57703. if (this.particleEmitterType.direction2) {
  57704. return this.particleEmitterType.direction2;
  57705. }
  57706. return BABYLON.Vector3.Zero();
  57707. },
  57708. set: function (value) {
  57709. if (this.particleEmitterType.direction2) {
  57710. this.particleEmitterType.direction2 = value;
  57711. }
  57712. },
  57713. enumerable: true,
  57714. configurable: true
  57715. });
  57716. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57717. /**
  57718. * 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.
  57719. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57720. */
  57721. get: function () {
  57722. if (this.particleEmitterType.minEmitBox) {
  57723. return this.particleEmitterType.minEmitBox;
  57724. }
  57725. return BABYLON.Vector3.Zero();
  57726. },
  57727. set: function (value) {
  57728. if (this.particleEmitterType.minEmitBox) {
  57729. this.particleEmitterType.minEmitBox = value;
  57730. }
  57731. },
  57732. enumerable: true,
  57733. configurable: true
  57734. });
  57735. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57736. /**
  57737. * 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.
  57738. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57739. */
  57740. get: function () {
  57741. if (this.particleEmitterType.maxEmitBox) {
  57742. return this.particleEmitterType.maxEmitBox;
  57743. }
  57744. return BABYLON.Vector3.Zero();
  57745. },
  57746. set: function (value) {
  57747. if (this.particleEmitterType.maxEmitBox) {
  57748. this.particleEmitterType.maxEmitBox = value;
  57749. }
  57750. },
  57751. enumerable: true,
  57752. configurable: true
  57753. });
  57754. /**
  57755. * Gets the maximum number of particles active at the same time.
  57756. * @returns The max number of active particles.
  57757. */
  57758. GPUParticleSystem.prototype.getCapacity = function () {
  57759. return this._capacity;
  57760. };
  57761. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57762. /**
  57763. * Gets or set the number of active particles
  57764. */
  57765. get: function () {
  57766. return this._activeCount;
  57767. },
  57768. set: function (value) {
  57769. this._activeCount = Math.min(value, this._capacity);
  57770. },
  57771. enumerable: true,
  57772. configurable: true
  57773. });
  57774. /**
  57775. * Is this system ready to be used/rendered
  57776. * @return true if the system is ready
  57777. */
  57778. GPUParticleSystem.prototype.isReady = function () {
  57779. if (!this._updateEffect) {
  57780. this._recreateUpdateEffect();
  57781. this._recreateRenderEffect();
  57782. return false;
  57783. }
  57784. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57785. return false;
  57786. }
  57787. return true;
  57788. };
  57789. /**
  57790. * Gets Wether the system has been started.
  57791. * @returns True if it has been started, otherwise false.
  57792. */
  57793. GPUParticleSystem.prototype.isStarted = function () {
  57794. return this._started;
  57795. };
  57796. /**
  57797. * Starts the particle system and begins to emit.
  57798. */
  57799. GPUParticleSystem.prototype.start = function () {
  57800. this._started = true;
  57801. this._stopped = false;
  57802. };
  57803. /**
  57804. * Stops the particle system.
  57805. */
  57806. GPUParticleSystem.prototype.stop = function () {
  57807. this._stopped = true;
  57808. };
  57809. /**
  57810. * Remove all active particles
  57811. */
  57812. GPUParticleSystem.prototype.reset = function () {
  57813. this._releaseBuffers();
  57814. this._releaseVAOs();
  57815. this._currentActiveCount = 0;
  57816. this._targetIndex = 0;
  57817. };
  57818. /**
  57819. * Returns the string "GPUParticleSystem"
  57820. * @returns a string containing the class name
  57821. */
  57822. GPUParticleSystem.prototype.getClassName = function () {
  57823. return "GPUParticleSystem";
  57824. };
  57825. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57826. var updateVertexBuffers = {};
  57827. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57828. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57829. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57830. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57831. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57832. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57833. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57834. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  57835. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57836. this._engine.bindArrayBuffer(null);
  57837. return vao;
  57838. };
  57839. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57840. var renderVertexBuffers = {};
  57841. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57842. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57843. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57844. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57845. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57846. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  57847. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57848. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57849. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57850. this._engine.bindArrayBuffer(null);
  57851. return vao;
  57852. };
  57853. GPUParticleSystem.prototype._initialize = function (force) {
  57854. if (force === void 0) { force = false; }
  57855. if (this._buffer0 && !force) {
  57856. return;
  57857. }
  57858. var engine = this._scene.getEngine();
  57859. var data = new Array();
  57860. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57861. // position
  57862. data.push(0.0);
  57863. data.push(0.0);
  57864. data.push(0.0);
  57865. // Age and life
  57866. data.push(0.0); // create the particle as a dead one to create a new one at start
  57867. data.push(0.0);
  57868. // Seed
  57869. data.push(Math.random());
  57870. // Size
  57871. data.push(0.0);
  57872. // color
  57873. data.push(0.0);
  57874. data.push(0.0);
  57875. data.push(0.0);
  57876. data.push(0.0);
  57877. // direction
  57878. data.push(0.0);
  57879. data.push(0.0);
  57880. data.push(0.0);
  57881. // angle
  57882. data.push(0.0);
  57883. data.push(0.0);
  57884. }
  57885. // Sprite data
  57886. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57887. -0.5, 0.5, 0, 1,
  57888. -0.5, -0.5, 0, 0,
  57889. 0.5, -0.5, 1, 0]);
  57890. // Buffers
  57891. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57892. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57893. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57894. // Update VAO
  57895. this._updateVAO = [];
  57896. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57897. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57898. // Render VAO
  57899. this._renderVAO = [];
  57900. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57901. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57902. // Links
  57903. this._sourceBuffer = this._buffer0;
  57904. this._targetBuffer = this._buffer1;
  57905. };
  57906. /** @hidden */
  57907. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57908. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57909. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57910. return;
  57911. }
  57912. this._updateEffectOptions.defines = defines;
  57913. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57914. };
  57915. /** @hidden */
  57916. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57917. var defines = "";
  57918. if (this._scene.clipPlane) {
  57919. defines = "\n#define CLIPPLANE";
  57920. }
  57921. if (this._renderEffect && this._renderEffect.defines === defines) {
  57922. return;
  57923. }
  57924. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57925. };
  57926. /**
  57927. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57928. */
  57929. GPUParticleSystem.prototype.animate = function () {
  57930. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57931. this._actualFrame += this._timeDelta;
  57932. if (!this._stopped) {
  57933. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57934. this.stop();
  57935. }
  57936. }
  57937. };
  57938. /**
  57939. * Renders the particle system in its current state.
  57940. * @returns the current number of particles
  57941. */
  57942. GPUParticleSystem.prototype.render = function () {
  57943. if (!this._started) {
  57944. return 0;
  57945. }
  57946. this._recreateUpdateEffect();
  57947. this._recreateRenderEffect();
  57948. if (!this.isReady()) {
  57949. return 0;
  57950. }
  57951. if (this._currentRenderId === this._scene.getRenderId()) {
  57952. return 0;
  57953. }
  57954. this._currentRenderId = this._scene.getRenderId();
  57955. // Get everything ready to render
  57956. this._initialize();
  57957. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57958. // Enable update effect
  57959. this._engine.enableEffect(this._updateEffect);
  57960. this._engine.setState(false);
  57961. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57962. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57963. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57964. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57965. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57966. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57967. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57968. this._updateEffect.setDirectColor4("color1", this.color1);
  57969. this._updateEffect.setDirectColor4("color2", this.color2);
  57970. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57971. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  57972. this._updateEffect.setVector3("gravity", this.gravity);
  57973. if (this.particleEmitterType) {
  57974. this.particleEmitterType.applyToShader(this._updateEffect);
  57975. }
  57976. var emitterWM;
  57977. if (this.emitter.position) {
  57978. var emitterMesh = this.emitter;
  57979. emitterWM = emitterMesh.getWorldMatrix();
  57980. }
  57981. else {
  57982. var emitterPosition = this.emitter;
  57983. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57984. }
  57985. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57986. // Bind source VAO
  57987. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57988. // Update
  57989. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57990. this._engine.setRasterizerState(false);
  57991. this._engine.beginTransformFeedback();
  57992. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57993. this._engine.endTransformFeedback();
  57994. this._engine.setRasterizerState(true);
  57995. this._engine.bindTransformFeedbackBuffer(null);
  57996. // Enable render effect
  57997. this._engine.enableEffect(this._renderEffect);
  57998. var viewMatrix = this._scene.getViewMatrix();
  57999. this._renderEffect.setMatrix("view", viewMatrix);
  58000. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58001. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58002. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58003. if (this._scene.clipPlane) {
  58004. var clipPlane = this._scene.clipPlane;
  58005. var invView = viewMatrix.clone();
  58006. invView.invert();
  58007. this._renderEffect.setMatrix("invView", invView);
  58008. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58009. }
  58010. // Draw order
  58011. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58012. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58013. }
  58014. else {
  58015. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58016. }
  58017. if (this.forceDepthWrite) {
  58018. this._engine.setDepthWrite(true);
  58019. }
  58020. // Bind source VAO
  58021. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58022. // Render
  58023. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58024. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58025. // Switch VAOs
  58026. this._targetIndex++;
  58027. if (this._targetIndex === 2) {
  58028. this._targetIndex = 0;
  58029. }
  58030. // Switch buffers
  58031. var tmpBuffer = this._sourceBuffer;
  58032. this._sourceBuffer = this._targetBuffer;
  58033. this._targetBuffer = tmpBuffer;
  58034. return this._currentActiveCount;
  58035. };
  58036. /**
  58037. * Rebuilds the particle system
  58038. */
  58039. GPUParticleSystem.prototype.rebuild = function () {
  58040. this._initialize(true);
  58041. };
  58042. GPUParticleSystem.prototype._releaseBuffers = function () {
  58043. if (this._buffer0) {
  58044. this._buffer0.dispose();
  58045. this._buffer0 = null;
  58046. }
  58047. if (this._buffer1) {
  58048. this._buffer1.dispose();
  58049. this._buffer1 = null;
  58050. }
  58051. if (this._spriteBuffer) {
  58052. this._spriteBuffer.dispose();
  58053. this._spriteBuffer = null;
  58054. }
  58055. };
  58056. GPUParticleSystem.prototype._releaseVAOs = function () {
  58057. if (!this._updateVAO) {
  58058. return;
  58059. }
  58060. for (var index = 0; index < this._updateVAO.length; index++) {
  58061. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58062. }
  58063. this._updateVAO = [];
  58064. for (var index = 0; index < this._renderVAO.length; index++) {
  58065. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58066. }
  58067. this._renderVAO = [];
  58068. };
  58069. /**
  58070. * Disposes the particle system and free the associated resources
  58071. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58072. */
  58073. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58074. if (disposeTexture === void 0) { disposeTexture = true; }
  58075. var index = this._scene.particleSystems.indexOf(this);
  58076. if (index > -1) {
  58077. this._scene.particleSystems.splice(index, 1);
  58078. }
  58079. this._releaseBuffers();
  58080. this._releaseVAOs();
  58081. if (this._randomTexture) {
  58082. this._randomTexture.dispose();
  58083. this._randomTexture = null;
  58084. }
  58085. if (disposeTexture && this.particleTexture) {
  58086. this.particleTexture.dispose();
  58087. this.particleTexture = null;
  58088. }
  58089. // Callback
  58090. this.onDisposeObservable.notifyObservers(this);
  58091. this.onDisposeObservable.clear();
  58092. };
  58093. /**
  58094. * Clones the particle system.
  58095. * @param name The name of the cloned object
  58096. * @param newEmitter The new emitter to use
  58097. * @returns the cloned particle system
  58098. */
  58099. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58100. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58101. BABYLON.Tools.DeepCopy(this, result);
  58102. if (newEmitter === undefined) {
  58103. newEmitter = this.emitter;
  58104. }
  58105. result.emitter = newEmitter;
  58106. if (this.particleTexture) {
  58107. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58108. }
  58109. return result;
  58110. };
  58111. /**
  58112. * Serializes the particle system to a JSON object.
  58113. * @returns the JSON object
  58114. */
  58115. GPUParticleSystem.prototype.serialize = function () {
  58116. var serializationObject = {};
  58117. serializationObject.name = this.name;
  58118. serializationObject.id = this.id;
  58119. // Emitter
  58120. if (this.emitter.position) {
  58121. var emitterMesh = this.emitter;
  58122. serializationObject.emitterId = emitterMesh.id;
  58123. }
  58124. else {
  58125. var emitterPosition = this.emitter;
  58126. serializationObject.emitter = emitterPosition.asArray();
  58127. }
  58128. serializationObject.capacity = this.getCapacity();
  58129. if (this.particleTexture) {
  58130. serializationObject.textureName = this.particleTexture.name;
  58131. }
  58132. // Animations
  58133. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58134. // Particle system
  58135. serializationObject.activeParticleCount = this.activeParticleCount;
  58136. serializationObject.randomTextureSize = this._randomTextureSize;
  58137. serializationObject.minSize = this.minSize;
  58138. serializationObject.maxSize = this.maxSize;
  58139. serializationObject.minEmitPower = this.minEmitPower;
  58140. serializationObject.maxEmitPower = this.maxEmitPower;
  58141. serializationObject.minLifeTime = this.minLifeTime;
  58142. serializationObject.maxLifeTime = this.maxLifeTime;
  58143. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58144. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58145. serializationObject.emitRate = this.emitRate;
  58146. serializationObject.gravity = this.gravity.asArray();
  58147. serializationObject.color1 = this.color1.asArray();
  58148. serializationObject.color2 = this.color2.asArray();
  58149. serializationObject.colorDead = this.colorDead.asArray();
  58150. serializationObject.updateSpeed = this.updateSpeed;
  58151. serializationObject.targetStopDuration = this.targetStopDuration;
  58152. serializationObject.blendMode = this.blendMode;
  58153. // Emitter
  58154. if (this.particleEmitterType) {
  58155. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58156. }
  58157. return serializationObject;
  58158. };
  58159. /**
  58160. * Parses a JSON object to create a GPU particle system.
  58161. * @param parsedParticleSystem The JSON object to parse
  58162. * @param scene The scene to create the particle system in
  58163. * @param rootUrl The root url to use to load external dependencies like texture
  58164. * @returns the parsed GPU particle system
  58165. */
  58166. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58167. var name = parsedParticleSystem.name;
  58168. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58169. if (parsedParticleSystem.id) {
  58170. particleSystem.id = parsedParticleSystem.id;
  58171. }
  58172. // Texture
  58173. if (parsedParticleSystem.textureName) {
  58174. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58175. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58176. }
  58177. // Emitter
  58178. if (parsedParticleSystem.emitterId) {
  58179. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58180. }
  58181. else {
  58182. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58183. }
  58184. // Animations
  58185. if (parsedParticleSystem.animations) {
  58186. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58187. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58188. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58189. }
  58190. }
  58191. // Particle system
  58192. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58193. particleSystem.minSize = parsedParticleSystem.minSize;
  58194. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58195. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58196. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58197. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58198. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58199. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58200. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58201. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58202. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58203. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58204. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58205. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58206. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58207. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58208. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58209. // Emitter
  58210. if (parsedParticleSystem.particleEmitterType) {
  58211. var emitterType = void 0;
  58212. switch (parsedParticleSystem.particleEmitterType.type) {
  58213. case "SphereEmitter":
  58214. emitterType = new BABYLON.SphereParticleEmitter();
  58215. break;
  58216. case "SphereDirectedParticleEmitter":
  58217. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58218. break;
  58219. case "ConeEmitter":
  58220. emitterType = new BABYLON.ConeParticleEmitter();
  58221. break;
  58222. case "BoxEmitter":
  58223. default:
  58224. emitterType = new BABYLON.BoxParticleEmitter();
  58225. break;
  58226. }
  58227. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58228. particleSystem.particleEmitterType = emitterType;
  58229. }
  58230. return particleSystem;
  58231. };
  58232. return GPUParticleSystem;
  58233. }());
  58234. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58235. })(BABYLON || (BABYLON = {}));
  58236. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58237. var BABYLON;
  58238. (function (BABYLON) {
  58239. /**
  58240. * Represents one particle of a solid particle system.
  58241. */
  58242. var SolidParticle = /** @class */ (function () {
  58243. /**
  58244. * Creates a Solid Particle object.
  58245. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58246. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58247. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58248. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58249. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58250. * @param shapeId (integer) is the model shape identifier in the SPS.
  58251. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58252. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58253. */
  58254. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58255. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58256. /**
  58257. * particle global index
  58258. */
  58259. this.idx = 0;
  58260. /**
  58261. * The color of the particle
  58262. */
  58263. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58264. /**
  58265. * The world space position of the particle.
  58266. */
  58267. this.position = BABYLON.Vector3.Zero();
  58268. /**
  58269. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58270. */
  58271. this.rotation = BABYLON.Vector3.Zero();
  58272. /**
  58273. * The scaling of the particle.
  58274. */
  58275. this.scaling = BABYLON.Vector3.One();
  58276. /**
  58277. * The uvs of the particle.
  58278. */
  58279. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58280. /**
  58281. * The current speed of the particle.
  58282. */
  58283. this.velocity = BABYLON.Vector3.Zero();
  58284. /**
  58285. * The pivot point in the particle local space.
  58286. */
  58287. this.pivot = BABYLON.Vector3.Zero();
  58288. /**
  58289. * Must the particle be translated from its pivot point in its local space ?
  58290. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58291. * Default : false
  58292. */
  58293. this.translateFromPivot = false;
  58294. /**
  58295. * Is the particle active or not ?
  58296. */
  58297. this.alive = true;
  58298. /**
  58299. * Is the particle visible or not ?
  58300. */
  58301. this.isVisible = true;
  58302. /**
  58303. * Index of this particle in the global "positions" array (Internal use)
  58304. */
  58305. this._pos = 0;
  58306. /**
  58307. * Index of this particle in the global "indices" array (Internal use)
  58308. */
  58309. this._ind = 0;
  58310. /**
  58311. * ModelShape id of this particle
  58312. */
  58313. this.shapeId = 0;
  58314. /**
  58315. * Index of the particle in its shape id (Internal use)
  58316. */
  58317. this.idxInShape = 0;
  58318. /**
  58319. * Still set as invisible in order to skip useless computations (Internal use)
  58320. */
  58321. this._stillInvisible = false;
  58322. /**
  58323. * Last computed particle rotation matrix
  58324. */
  58325. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58326. /**
  58327. * Parent particle Id, if any.
  58328. * Default null.
  58329. */
  58330. this.parentId = null;
  58331. /**
  58332. * Internal global position in the SPS.
  58333. */
  58334. this._globalPosition = BABYLON.Vector3.Zero();
  58335. this.idx = particleIndex;
  58336. this._pos = positionIndex;
  58337. this._ind = indiceIndex;
  58338. this._model = model;
  58339. this.shapeId = shapeId;
  58340. this.idxInShape = idxInShape;
  58341. this._sps = sps;
  58342. if (modelBoundingInfo) {
  58343. this._modelBoundingInfo = modelBoundingInfo;
  58344. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58345. }
  58346. }
  58347. Object.defineProperty(SolidParticle.prototype, "scale", {
  58348. /**
  58349. * Legacy support, changed scale to scaling
  58350. */
  58351. get: function () {
  58352. return this.scaling;
  58353. },
  58354. /**
  58355. * Legacy support, changed scale to scaling
  58356. */
  58357. set: function (scale) {
  58358. this.scaling = scale;
  58359. },
  58360. enumerable: true,
  58361. configurable: true
  58362. });
  58363. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58364. /**
  58365. * Legacy support, changed quaternion to rotationQuaternion
  58366. */
  58367. get: function () {
  58368. return this.rotationQuaternion;
  58369. },
  58370. /**
  58371. * Legacy support, changed quaternion to rotationQuaternion
  58372. */
  58373. set: function (q) {
  58374. this.rotationQuaternion = q;
  58375. },
  58376. enumerable: true,
  58377. configurable: true
  58378. });
  58379. /**
  58380. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58381. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58382. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58383. * @returns true if it intersects
  58384. */
  58385. SolidParticle.prototype.intersectsMesh = function (target) {
  58386. if (!this._boundingInfo || !target._boundingInfo) {
  58387. return false;
  58388. }
  58389. if (this._sps._bSphereOnly) {
  58390. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58391. }
  58392. return this._boundingInfo.intersects(target._boundingInfo, false);
  58393. };
  58394. return SolidParticle;
  58395. }());
  58396. BABYLON.SolidParticle = SolidParticle;
  58397. /**
  58398. * Represents the shape of the model used by one particle of a solid particle system.
  58399. * SPS internal tool, don't use it manually.
  58400. */
  58401. var ModelShape = /** @class */ (function () {
  58402. /**
  58403. * 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.
  58404. * SPS internal tool, don't use it manually.
  58405. * @hidden
  58406. */
  58407. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58408. /**
  58409. * length of the shape in the model indices array (internal use)
  58410. */
  58411. this._indicesLength = 0;
  58412. this.shapeID = id;
  58413. this._shape = shape;
  58414. this._indicesLength = indicesLength;
  58415. this._shapeUV = shapeUV;
  58416. this._positionFunction = posFunction;
  58417. this._vertexFunction = vtxFunction;
  58418. }
  58419. return ModelShape;
  58420. }());
  58421. BABYLON.ModelShape = ModelShape;
  58422. /**
  58423. * Represents a Depth Sorted Particle in the solid particle system.
  58424. */
  58425. var DepthSortedParticle = /** @class */ (function () {
  58426. function DepthSortedParticle() {
  58427. /**
  58428. * Index of the particle in the "indices" array
  58429. */
  58430. this.ind = 0;
  58431. /**
  58432. * Length of the particle shape in the "indices" array
  58433. */
  58434. this.indicesLength = 0;
  58435. /**
  58436. * Squared distance from the particle to the camera
  58437. */
  58438. this.sqDistance = 0.0;
  58439. }
  58440. return DepthSortedParticle;
  58441. }());
  58442. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58443. })(BABYLON || (BABYLON = {}));
  58444. //# sourceMappingURL=babylon.solidParticle.js.map
  58445. var BABYLON;
  58446. (function (BABYLON) {
  58447. /**
  58448. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58449. *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.
  58450. * The SPS is also a particle system. It provides some methods to manage the particles.
  58451. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58452. *
  58453. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58454. */
  58455. var SolidParticleSystem = /** @class */ (function () {
  58456. /**
  58457. * Creates a SPS (Solid Particle System) object.
  58458. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58459. * @param scene (Scene) is the scene in which the SPS is added.
  58460. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58461. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58462. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58463. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58464. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58465. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58466. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58467. */
  58468. function SolidParticleSystem(name, scene, options) {
  58469. /**
  58470. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58471. * Example : var p = SPS.particles[i];
  58472. */
  58473. this.particles = new Array();
  58474. /**
  58475. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58476. */
  58477. this.nbParticles = 0;
  58478. /**
  58479. * If the particles must ever face the camera (default false). Useful for planar particles.
  58480. */
  58481. this.billboard = false;
  58482. /**
  58483. * Recompute normals when adding a shape
  58484. */
  58485. this.recomputeNormals = true;
  58486. /**
  58487. * This a counter ofr your own usage. It's not set by any SPS functions.
  58488. */
  58489. this.counter = 0;
  58490. /**
  58491. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58492. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58493. */
  58494. this.vars = {};
  58495. /**
  58496. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58497. */
  58498. this._bSphereOnly = false;
  58499. /**
  58500. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58501. */
  58502. this._bSphereRadiusFactor = 1.0;
  58503. this._positions = new Array();
  58504. this._indices = new Array();
  58505. this._normals = new Array();
  58506. this._colors = new Array();
  58507. this._uvs = new Array();
  58508. this._index = 0; // indices index
  58509. this._updatable = true;
  58510. this._pickable = false;
  58511. this._isVisibilityBoxLocked = false;
  58512. this._alwaysVisible = false;
  58513. this._depthSort = false;
  58514. this._shapeCounter = 0;
  58515. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58516. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58517. this._computeParticleColor = true;
  58518. this._computeParticleTexture = true;
  58519. this._computeParticleRotation = true;
  58520. this._computeParticleVertex = false;
  58521. this._computeBoundingBox = false;
  58522. this._depthSortParticles = true;
  58523. this._cam_axisZ = BABYLON.Vector3.Zero();
  58524. this._cam_axisY = BABYLON.Vector3.Zero();
  58525. this._cam_axisX = BABYLON.Vector3.Zero();
  58526. this._axisZ = BABYLON.Axis.Z;
  58527. this._camDir = BABYLON.Vector3.Zero();
  58528. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58529. this._rotMatrix = new BABYLON.Matrix();
  58530. this._invertMatrix = new BABYLON.Matrix();
  58531. this._rotated = BABYLON.Vector3.Zero();
  58532. this._quaternion = new BABYLON.Quaternion();
  58533. this._vertex = BABYLON.Vector3.Zero();
  58534. this._normal = BABYLON.Vector3.Zero();
  58535. this._yaw = 0.0;
  58536. this._pitch = 0.0;
  58537. this._roll = 0.0;
  58538. this._halfroll = 0.0;
  58539. this._halfpitch = 0.0;
  58540. this._halfyaw = 0.0;
  58541. this._sinRoll = 0.0;
  58542. this._cosRoll = 0.0;
  58543. this._sinPitch = 0.0;
  58544. this._cosPitch = 0.0;
  58545. this._sinYaw = 0.0;
  58546. this._cosYaw = 0.0;
  58547. this._mustUnrotateFixedNormals = false;
  58548. this._minimum = BABYLON.Vector3.Zero();
  58549. this._maximum = BABYLON.Vector3.Zero();
  58550. this._minBbox = BABYLON.Vector3.Zero();
  58551. this._maxBbox = BABYLON.Vector3.Zero();
  58552. this._particlesIntersect = false;
  58553. this._depthSortFunction = function (p1, p2) {
  58554. return (p2.sqDistance - p1.sqDistance);
  58555. };
  58556. this._needs32Bits = false;
  58557. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58558. this._scaledPivot = BABYLON.Vector3.Zero();
  58559. this._particleHasParent = false;
  58560. this.name = name;
  58561. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58562. this._camera = scene.activeCamera;
  58563. this._pickable = options ? options.isPickable : false;
  58564. this._depthSort = options ? options.enableDepthSort : false;
  58565. this._particlesIntersect = options ? options.particleIntersection : false;
  58566. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58567. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58568. if (options && options.updatable) {
  58569. this._updatable = options.updatable;
  58570. }
  58571. else {
  58572. this._updatable = true;
  58573. }
  58574. if (this._pickable) {
  58575. this.pickedParticles = [];
  58576. }
  58577. if (this._depthSort) {
  58578. this.depthSortedParticles = [];
  58579. }
  58580. }
  58581. /**
  58582. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58583. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58584. * @returns the created mesh
  58585. */
  58586. SolidParticleSystem.prototype.buildMesh = function () {
  58587. if (this.nbParticles === 0) {
  58588. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58589. this.addShape(triangle, 1);
  58590. triangle.dispose();
  58591. }
  58592. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58593. this._positions32 = new Float32Array(this._positions);
  58594. this._uvs32 = new Float32Array(this._uvs);
  58595. this._colors32 = new Float32Array(this._colors);
  58596. if (this.recomputeNormals) {
  58597. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58598. }
  58599. this._normals32 = new Float32Array(this._normals);
  58600. this._fixedNormal32 = new Float32Array(this._normals);
  58601. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58602. this._unrotateFixedNormals();
  58603. }
  58604. var vertexData = new BABYLON.VertexData();
  58605. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58606. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58607. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58608. if (this._uvs32.length > 0) {
  58609. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58610. }
  58611. if (this._colors32.length > 0) {
  58612. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58613. }
  58614. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58615. vertexData.applyToMesh(mesh, this._updatable);
  58616. this.mesh = mesh;
  58617. this.mesh.isPickable = this._pickable;
  58618. // free memory
  58619. if (!this._depthSort) {
  58620. this._indices = null;
  58621. }
  58622. this._positions = null;
  58623. this._normals = null;
  58624. this._uvs = null;
  58625. this._colors = null;
  58626. if (!this._updatable) {
  58627. this.particles.length = 0;
  58628. }
  58629. return mesh;
  58630. };
  58631. /**
  58632. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58633. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58634. * Thus the particles generated from `digest()` have their property `position` set yet.
  58635. * @param mesh ( Mesh ) is the mesh to be digested
  58636. * @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
  58637. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58638. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58639. * @returns the current SPS
  58640. */
  58641. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58642. var size = (options && options.facetNb) || 1;
  58643. var number = (options && options.number) || 0;
  58644. var delta = (options && options.delta) || 0;
  58645. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58646. var meshInd = mesh.getIndices();
  58647. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58648. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58649. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58650. var f = 0; // facet counter
  58651. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58652. // compute size from number
  58653. if (number) {
  58654. number = (number > totalFacets) ? totalFacets : number;
  58655. size = Math.round(totalFacets / number);
  58656. delta = 0;
  58657. }
  58658. else {
  58659. size = (size > totalFacets) ? totalFacets : size;
  58660. }
  58661. var facetPos = []; // submesh positions
  58662. var facetInd = []; // submesh indices
  58663. var facetUV = []; // submesh UV
  58664. var facetCol = []; // submesh colors
  58665. var barycenter = BABYLON.Vector3.Zero();
  58666. var sizeO = size;
  58667. while (f < totalFacets) {
  58668. size = sizeO + Math.floor((1 + delta) * Math.random());
  58669. if (f > totalFacets - size) {
  58670. size = totalFacets - f;
  58671. }
  58672. // reset temp arrays
  58673. facetPos.length = 0;
  58674. facetInd.length = 0;
  58675. facetUV.length = 0;
  58676. facetCol.length = 0;
  58677. // iterate over "size" facets
  58678. var fi = 0;
  58679. for (var j = f * 3; j < (f + size) * 3; j++) {
  58680. facetInd.push(fi);
  58681. var i = meshInd[j];
  58682. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58683. if (meshUV) {
  58684. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58685. }
  58686. if (meshCol) {
  58687. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58688. }
  58689. fi++;
  58690. }
  58691. // create a model shape for each single particle
  58692. var idx = this.nbParticles;
  58693. var shape = this._posToShape(facetPos);
  58694. var shapeUV = this._uvsToShapeUV(facetUV);
  58695. // compute the barycenter of the shape
  58696. var v;
  58697. for (v = 0; v < shape.length; v++) {
  58698. barycenter.addInPlace(shape[v]);
  58699. }
  58700. barycenter.scaleInPlace(1 / shape.length);
  58701. // shift the shape from its barycenter to the origin
  58702. for (v = 0; v < shape.length; v++) {
  58703. shape[v].subtractInPlace(barycenter);
  58704. }
  58705. var bInfo;
  58706. if (this._particlesIntersect) {
  58707. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58708. }
  58709. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58710. // add the particle in the SPS
  58711. var currentPos = this._positions.length;
  58712. var currentInd = this._indices.length;
  58713. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58714. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58715. // initialize the particle position
  58716. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58717. this._index += shape.length;
  58718. idx++;
  58719. this.nbParticles++;
  58720. this._shapeCounter++;
  58721. f += size;
  58722. }
  58723. return this;
  58724. };
  58725. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58726. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58727. var index = 0;
  58728. var idx = 0;
  58729. for (var p = 0; p < this.particles.length; p++) {
  58730. this._particle = this.particles[p];
  58731. this._shape = this._particle._model._shape;
  58732. if (this._particle.rotationQuaternion) {
  58733. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58734. }
  58735. else {
  58736. this._yaw = this._particle.rotation.y;
  58737. this._pitch = this._particle.rotation.x;
  58738. this._roll = this._particle.rotation.z;
  58739. this._quaternionRotationYPR();
  58740. }
  58741. this._quaternionToRotationMatrix();
  58742. this._rotMatrix.invertToRef(this._invertMatrix);
  58743. for (var pt = 0; pt < this._shape.length; pt++) {
  58744. idx = index + pt * 3;
  58745. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58746. this._fixedNormal32[idx] = this._normal.x;
  58747. this._fixedNormal32[idx + 1] = this._normal.y;
  58748. this._fixedNormal32[idx + 2] = this._normal.z;
  58749. }
  58750. index = idx + 3;
  58751. }
  58752. };
  58753. //reset copy
  58754. SolidParticleSystem.prototype._resetCopy = function () {
  58755. this._copy.position.x = 0;
  58756. this._copy.position.y = 0;
  58757. this._copy.position.z = 0;
  58758. this._copy.rotation.x = 0;
  58759. this._copy.rotation.y = 0;
  58760. this._copy.rotation.z = 0;
  58761. this._copy.rotationQuaternion = null;
  58762. this._copy.scaling.x = 1.0;
  58763. this._copy.scaling.y = 1.0;
  58764. this._copy.scaling.z = 1.0;
  58765. this._copy.uvs.x = 0;
  58766. this._copy.uvs.y = 0;
  58767. this._copy.uvs.z = 1.0;
  58768. this._copy.uvs.w = 1.0;
  58769. this._copy.color = null;
  58770. this._copy.translateFromPivot = false;
  58771. };
  58772. // _meshBuilder : inserts the shape model in the global SPS mesh
  58773. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58774. var i;
  58775. var u = 0;
  58776. var c = 0;
  58777. var n = 0;
  58778. this._resetCopy();
  58779. if (options && options.positionFunction) { // call to custom positionFunction
  58780. options.positionFunction(this._copy, idx, idxInShape);
  58781. this._mustUnrotateFixedNormals = true;
  58782. }
  58783. if (this._copy.rotationQuaternion) {
  58784. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58785. }
  58786. else {
  58787. this._yaw = this._copy.rotation.y;
  58788. this._pitch = this._copy.rotation.x;
  58789. this._roll = this._copy.rotation.z;
  58790. this._quaternionRotationYPR();
  58791. }
  58792. this._quaternionToRotationMatrix();
  58793. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58794. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58795. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58796. if (this._copy.translateFromPivot) {
  58797. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58798. }
  58799. else {
  58800. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58801. }
  58802. for (i = 0; i < shape.length; i++) {
  58803. this._vertex.x = shape[i].x;
  58804. this._vertex.y = shape[i].y;
  58805. this._vertex.z = shape[i].z;
  58806. if (options && options.vertexFunction) {
  58807. options.vertexFunction(this._copy, this._vertex, i);
  58808. }
  58809. this._vertex.x *= this._copy.scaling.x;
  58810. this._vertex.y *= this._copy.scaling.y;
  58811. this._vertex.z *= this._copy.scaling.z;
  58812. this._vertex.x -= this._scaledPivot.x;
  58813. this._vertex.y -= this._scaledPivot.y;
  58814. this._vertex.z -= this._scaledPivot.z;
  58815. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58816. this._rotated.addInPlace(this._pivotBackTranslation);
  58817. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58818. if (meshUV) {
  58819. 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);
  58820. u += 2;
  58821. }
  58822. if (this._copy.color) {
  58823. this._color = this._copy.color;
  58824. }
  58825. else if (meshCol && meshCol[c] !== undefined) {
  58826. this._color.r = meshCol[c];
  58827. this._color.g = meshCol[c + 1];
  58828. this._color.b = meshCol[c + 2];
  58829. this._color.a = meshCol[c + 3];
  58830. }
  58831. else {
  58832. this._color.r = 1.0;
  58833. this._color.g = 1.0;
  58834. this._color.b = 1.0;
  58835. this._color.a = 1.0;
  58836. }
  58837. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58838. c += 4;
  58839. if (!this.recomputeNormals && meshNor) {
  58840. this._normal.x = meshNor[n];
  58841. this._normal.y = meshNor[n + 1];
  58842. this._normal.z = meshNor[n + 2];
  58843. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58844. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58845. n += 3;
  58846. }
  58847. }
  58848. for (i = 0; i < meshInd.length; i++) {
  58849. var current_ind = p + meshInd[i];
  58850. indices.push(current_ind);
  58851. if (current_ind > 65535) {
  58852. this._needs32Bits = true;
  58853. }
  58854. }
  58855. if (this._pickable) {
  58856. var nbfaces = meshInd.length / 3;
  58857. for (i = 0; i < nbfaces; i++) {
  58858. this.pickedParticles.push({ idx: idx, faceId: i });
  58859. }
  58860. }
  58861. if (this._depthSort) {
  58862. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58863. }
  58864. return this._copy;
  58865. };
  58866. // returns a shape array from positions array
  58867. SolidParticleSystem.prototype._posToShape = function (positions) {
  58868. var shape = [];
  58869. for (var i = 0; i < positions.length; i += 3) {
  58870. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58871. }
  58872. return shape;
  58873. };
  58874. // returns a shapeUV array from a Vector4 uvs
  58875. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58876. var shapeUV = [];
  58877. if (uvs) {
  58878. for (var i = 0; i < uvs.length; i++)
  58879. shapeUV.push(uvs[i]);
  58880. }
  58881. return shapeUV;
  58882. };
  58883. // adds a new particle object in the particles array
  58884. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58885. if (bInfo === void 0) { bInfo = null; }
  58886. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58887. this.particles.push(sp);
  58888. return sp;
  58889. };
  58890. /**
  58891. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58892. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58893. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58894. * @param nb (positive integer) the number of particles to be created from this model
  58895. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58896. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58897. * @returns the number of shapes in the system
  58898. */
  58899. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58900. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58901. var meshInd = mesh.getIndices();
  58902. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58903. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58904. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58905. var bbInfo;
  58906. if (this._particlesIntersect) {
  58907. bbInfo = mesh.getBoundingInfo();
  58908. }
  58909. var shape = this._posToShape(meshPos);
  58910. var shapeUV = this._uvsToShapeUV(meshUV);
  58911. var posfunc = options ? options.positionFunction : null;
  58912. var vtxfunc = options ? options.vertexFunction : null;
  58913. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58914. // particles
  58915. var sp;
  58916. var currentCopy;
  58917. var idx = this.nbParticles;
  58918. for (var i = 0; i < nb; i++) {
  58919. var currentPos = this._positions.length;
  58920. var currentInd = this._indices.length;
  58921. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58922. if (this._updatable) {
  58923. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58924. sp.position.copyFrom(currentCopy.position);
  58925. sp.rotation.copyFrom(currentCopy.rotation);
  58926. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58927. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58928. }
  58929. if (currentCopy.color && sp.color) {
  58930. sp.color.copyFrom(currentCopy.color);
  58931. }
  58932. sp.scaling.copyFrom(currentCopy.scaling);
  58933. sp.uvs.copyFrom(currentCopy.uvs);
  58934. }
  58935. this._index += shape.length;
  58936. idx++;
  58937. }
  58938. this.nbParticles += nb;
  58939. this._shapeCounter++;
  58940. return this._shapeCounter - 1;
  58941. };
  58942. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58943. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58944. this._resetCopy();
  58945. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58946. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58947. }
  58948. if (this._copy.rotationQuaternion) {
  58949. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58950. }
  58951. else {
  58952. this._yaw = this._copy.rotation.y;
  58953. this._pitch = this._copy.rotation.x;
  58954. this._roll = this._copy.rotation.z;
  58955. this._quaternionRotationYPR();
  58956. }
  58957. this._quaternionToRotationMatrix();
  58958. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58959. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58960. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58961. if (this._copy.translateFromPivot) {
  58962. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58963. }
  58964. else {
  58965. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58966. }
  58967. this._shape = particle._model._shape;
  58968. for (var pt = 0; pt < this._shape.length; pt++) {
  58969. this._vertex.x = this._shape[pt].x;
  58970. this._vertex.y = this._shape[pt].y;
  58971. this._vertex.z = this._shape[pt].z;
  58972. if (particle._model._vertexFunction) {
  58973. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58974. }
  58975. this._vertex.x *= this._copy.scaling.x;
  58976. this._vertex.y *= this._copy.scaling.y;
  58977. this._vertex.z *= this._copy.scaling.z;
  58978. this._vertex.x -= this._scaledPivot.x;
  58979. this._vertex.y -= this._scaledPivot.y;
  58980. this._vertex.z -= this._scaledPivot.z;
  58981. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58982. this._rotated.addInPlace(this._pivotBackTranslation);
  58983. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58984. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58985. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58986. }
  58987. particle.position.x = 0.0;
  58988. particle.position.y = 0.0;
  58989. particle.position.z = 0.0;
  58990. particle.rotation.x = 0.0;
  58991. particle.rotation.y = 0.0;
  58992. particle.rotation.z = 0.0;
  58993. particle.rotationQuaternion = null;
  58994. particle.scaling.x = 1.0;
  58995. particle.scaling.y = 1.0;
  58996. particle.scaling.z = 1.0;
  58997. particle.uvs.x = 0.0;
  58998. particle.uvs.y = 0.0;
  58999. particle.uvs.z = 1.0;
  59000. particle.uvs.w = 1.0;
  59001. particle.pivot.x = 0.0;
  59002. particle.pivot.y = 0.0;
  59003. particle.pivot.z = 0.0;
  59004. particle.translateFromPivot = false;
  59005. particle.parentId = null;
  59006. };
  59007. /**
  59008. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59009. * @returns the SPS.
  59010. */
  59011. SolidParticleSystem.prototype.rebuildMesh = function () {
  59012. for (var p = 0; p < this.particles.length; p++) {
  59013. this._rebuildParticle(this.particles[p]);
  59014. }
  59015. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59016. return this;
  59017. };
  59018. /**
  59019. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59020. * This method calls `updateParticle()` for each particle of the SPS.
  59021. * For an animated SPS, it is usually called within the render loop.
  59022. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59023. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59024. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59025. * @returns the SPS.
  59026. */
  59027. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59028. if (start === void 0) { start = 0; }
  59029. if (end === void 0) { end = this.nbParticles - 1; }
  59030. if (update === void 0) { update = true; }
  59031. if (!this._updatable) {
  59032. return this;
  59033. }
  59034. // custom beforeUpdate
  59035. this.beforeUpdateParticles(start, end, update);
  59036. this._cam_axisX.x = 1.0;
  59037. this._cam_axisX.y = 0.0;
  59038. this._cam_axisX.z = 0.0;
  59039. this._cam_axisY.x = 0.0;
  59040. this._cam_axisY.y = 1.0;
  59041. this._cam_axisY.z = 0.0;
  59042. this._cam_axisZ.x = 0.0;
  59043. this._cam_axisZ.y = 0.0;
  59044. this._cam_axisZ.z = 1.0;
  59045. // cases when the World Matrix is to be computed first
  59046. if (this.billboard || this._depthSort) {
  59047. this.mesh.computeWorldMatrix(true);
  59048. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59049. }
  59050. // if the particles will always face the camera
  59051. if (this.billboard) {
  59052. // compute the camera position and un-rotate it by the current mesh rotation
  59053. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59054. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59055. this._cam_axisZ.normalize();
  59056. // same for camera up vector extracted from the cam view matrix
  59057. var view = this._camera.getViewMatrix(true);
  59058. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59059. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59060. this._cam_axisY.normalize();
  59061. this._cam_axisX.normalize();
  59062. }
  59063. // if depthSort, compute the camera global position in the mesh local system
  59064. if (this._depthSort) {
  59065. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59066. }
  59067. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59068. var idx = 0; // current position index in the global array positions32
  59069. var index = 0; // position start index in the global array positions32 of the current particle
  59070. var colidx = 0; // current color index in the global array colors32
  59071. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59072. var uvidx = 0; // current uv index in the global array uvs32
  59073. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59074. var pt = 0; // current index in the particle model shape
  59075. if (this.mesh.isFacetDataEnabled) {
  59076. this._computeBoundingBox = true;
  59077. }
  59078. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59079. if (this._computeBoundingBox) {
  59080. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59081. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59082. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59083. }
  59084. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59085. if (this.mesh._boundingInfo) {
  59086. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59087. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59088. }
  59089. }
  59090. }
  59091. // particle loop
  59092. index = this.particles[start]._pos;
  59093. var vpos = (index / 3) | 0;
  59094. colorIndex = vpos * 4;
  59095. uvIndex = vpos * 2;
  59096. for (var p = start; p <= end; p++) {
  59097. this._particle = this.particles[p];
  59098. this._shape = this._particle._model._shape;
  59099. this._shapeUV = this._particle._model._shapeUV;
  59100. // call to custom user function to update the particle properties
  59101. this.updateParticle(this._particle);
  59102. // camera-particle distance for depth sorting
  59103. if (this._depthSort && this._depthSortParticles) {
  59104. var dsp = this.depthSortedParticles[p];
  59105. dsp.ind = this._particle._ind;
  59106. dsp.indicesLength = this._particle._model._indicesLength;
  59107. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59108. }
  59109. // skip the computations for inactive or already invisible particles
  59110. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59111. // increment indexes for the next particle
  59112. pt = this._shape.length;
  59113. index += pt * 3;
  59114. colorIndex += pt * 4;
  59115. uvIndex += pt * 2;
  59116. continue;
  59117. }
  59118. if (this._particle.isVisible) {
  59119. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59120. this._particleHasParent = (this._particle.parentId !== null);
  59121. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59122. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59123. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59124. // particle rotation matrix
  59125. if (this.billboard) {
  59126. this._particle.rotation.x = 0.0;
  59127. this._particle.rotation.y = 0.0;
  59128. }
  59129. if (this._computeParticleRotation || this.billboard) {
  59130. if (this._particle.rotationQuaternion) {
  59131. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59132. }
  59133. else {
  59134. this._yaw = this._particle.rotation.y;
  59135. this._pitch = this._particle.rotation.x;
  59136. this._roll = this._particle.rotation.z;
  59137. this._quaternionRotationYPR();
  59138. }
  59139. this._quaternionToRotationMatrix();
  59140. }
  59141. if (this._particleHasParent) {
  59142. this._parent = this.particles[this._particle.parentId];
  59143. 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];
  59144. 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];
  59145. 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];
  59146. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59147. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59148. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59149. if (this._computeParticleRotation || this.billboard) {
  59150. 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];
  59151. 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];
  59152. 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];
  59153. 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];
  59154. 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];
  59155. 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];
  59156. 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];
  59157. 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];
  59158. 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];
  59159. }
  59160. }
  59161. else {
  59162. this._particle._globalPosition.x = this._particle.position.x;
  59163. this._particle._globalPosition.y = this._particle.position.y;
  59164. this._particle._globalPosition.z = this._particle.position.z;
  59165. if (this._computeParticleRotation || this.billboard) {
  59166. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59167. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59168. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59169. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59170. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59171. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59172. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59173. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59174. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59175. }
  59176. }
  59177. if (this._particle.translateFromPivot) {
  59178. this._pivotBackTranslation.x = 0.0;
  59179. this._pivotBackTranslation.y = 0.0;
  59180. this._pivotBackTranslation.z = 0.0;
  59181. }
  59182. else {
  59183. this._pivotBackTranslation.x = this._scaledPivot.x;
  59184. this._pivotBackTranslation.y = this._scaledPivot.y;
  59185. this._pivotBackTranslation.z = this._scaledPivot.z;
  59186. }
  59187. // particle vertex loop
  59188. for (pt = 0; pt < this._shape.length; pt++) {
  59189. idx = index + pt * 3;
  59190. colidx = colorIndex + pt * 4;
  59191. uvidx = uvIndex + pt * 2;
  59192. this._vertex.x = this._shape[pt].x;
  59193. this._vertex.y = this._shape[pt].y;
  59194. this._vertex.z = this._shape[pt].z;
  59195. if (this._computeParticleVertex) {
  59196. this.updateParticleVertex(this._particle, this._vertex, pt);
  59197. }
  59198. // positions
  59199. this._vertex.x *= this._particle.scaling.x;
  59200. this._vertex.y *= this._particle.scaling.y;
  59201. this._vertex.z *= this._particle.scaling.z;
  59202. this._vertex.x -= this._scaledPivot.x;
  59203. this._vertex.y -= this._scaledPivot.y;
  59204. this._vertex.z -= this._scaledPivot.z;
  59205. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59206. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59207. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59208. this._rotated.x += this._pivotBackTranslation.x;
  59209. this._rotated.y += this._pivotBackTranslation.y;
  59210. this._rotated.z += this._pivotBackTranslation.z;
  59211. 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;
  59212. 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;
  59213. 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;
  59214. if (this._computeBoundingBox) {
  59215. if (this._positions32[idx] < this._minimum.x) {
  59216. this._minimum.x = this._positions32[idx];
  59217. }
  59218. if (this._positions32[idx] > this._maximum.x) {
  59219. this._maximum.x = this._positions32[idx];
  59220. }
  59221. if (this._positions32[idx + 1] < this._minimum.y) {
  59222. this._minimum.y = this._positions32[idx + 1];
  59223. }
  59224. if (this._positions32[idx + 1] > this._maximum.y) {
  59225. this._maximum.y = this._positions32[idx + 1];
  59226. }
  59227. if (this._positions32[idx + 2] < this._minimum.z) {
  59228. this._minimum.z = this._positions32[idx + 2];
  59229. }
  59230. if (this._positions32[idx + 2] > this._maximum.z) {
  59231. this._maximum.z = this._positions32[idx + 2];
  59232. }
  59233. }
  59234. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59235. if (!this._computeParticleVertex) {
  59236. this._normal.x = this._fixedNormal32[idx];
  59237. this._normal.y = this._fixedNormal32[idx + 1];
  59238. this._normal.z = this._fixedNormal32[idx + 2];
  59239. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59240. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59241. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59242. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59243. 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;
  59244. 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;
  59245. }
  59246. if (this._computeParticleColor && this._particle.color) {
  59247. this._colors32[colidx] = this._particle.color.r;
  59248. this._colors32[colidx + 1] = this._particle.color.g;
  59249. this._colors32[colidx + 2] = this._particle.color.b;
  59250. this._colors32[colidx + 3] = this._particle.color.a;
  59251. }
  59252. if (this._computeParticleTexture) {
  59253. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59254. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59255. }
  59256. }
  59257. }
  59258. // particle just set invisible : scaled to zero and positioned at the origin
  59259. else {
  59260. this._particle._stillInvisible = true; // mark the particle as invisible
  59261. for (pt = 0; pt < this._shape.length; pt++) {
  59262. idx = index + pt * 3;
  59263. colidx = colorIndex + pt * 4;
  59264. uvidx = uvIndex + pt * 2;
  59265. this._positions32[idx] = 0.0;
  59266. this._positions32[idx + 1] = 0.0;
  59267. this._positions32[idx + 2] = 0.0;
  59268. this._normals32[idx] = 0.0;
  59269. this._normals32[idx + 1] = 0.0;
  59270. this._normals32[idx + 2] = 0.0;
  59271. if (this._computeParticleColor && this._particle.color) {
  59272. this._colors32[colidx] = this._particle.color.r;
  59273. this._colors32[colidx + 1] = this._particle.color.g;
  59274. this._colors32[colidx + 2] = this._particle.color.b;
  59275. this._colors32[colidx + 3] = this._particle.color.a;
  59276. }
  59277. if (this._computeParticleTexture) {
  59278. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59279. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59280. }
  59281. }
  59282. }
  59283. // if the particle intersections must be computed : update the bbInfo
  59284. if (this._particlesIntersect) {
  59285. var bInfo = this._particle._boundingInfo;
  59286. var bBox = bInfo.boundingBox;
  59287. var bSphere = bInfo.boundingSphere;
  59288. if (!this._bSphereOnly) {
  59289. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59290. for (var b = 0; b < bBox.vectors.length; b++) {
  59291. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59292. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59293. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59294. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59295. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59296. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59297. 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;
  59298. 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;
  59299. 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;
  59300. }
  59301. bBox._update(this.mesh._worldMatrix);
  59302. }
  59303. // place and scale the particle bouding sphere in the SPS local system, then update it
  59304. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59305. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59306. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59307. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59308. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59309. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59310. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59311. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59312. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59313. 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));
  59314. bSphere._update(this.mesh._worldMatrix);
  59315. }
  59316. // increment indexes for the next particle
  59317. index = idx + 3;
  59318. colorIndex = colidx + 4;
  59319. uvIndex = uvidx + 2;
  59320. }
  59321. // if the VBO must be updated
  59322. if (update) {
  59323. if (this._computeParticleColor) {
  59324. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59325. }
  59326. if (this._computeParticleTexture) {
  59327. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59328. }
  59329. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59330. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59331. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59332. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59333. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59334. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59335. for (var i = 0; i < this._normals32.length; i++) {
  59336. this._fixedNormal32[i] = this._normals32[i];
  59337. }
  59338. }
  59339. if (!this.mesh.areNormalsFrozen) {
  59340. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59341. }
  59342. }
  59343. if (this._depthSort && this._depthSortParticles) {
  59344. this.depthSortedParticles.sort(this._depthSortFunction);
  59345. var dspl = this.depthSortedParticles.length;
  59346. var sorted = 0;
  59347. var lind = 0;
  59348. var sind = 0;
  59349. var sid = 0;
  59350. for (sorted = 0; sorted < dspl; sorted++) {
  59351. lind = this.depthSortedParticles[sorted].indicesLength;
  59352. sind = this.depthSortedParticles[sorted].ind;
  59353. for (var i = 0; i < lind; i++) {
  59354. this._indices32[sid] = this._indices[sind + i];
  59355. sid++;
  59356. }
  59357. }
  59358. this.mesh.updateIndices(this._indices32);
  59359. }
  59360. }
  59361. if (this._computeBoundingBox) {
  59362. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59363. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59364. }
  59365. this.afterUpdateParticles(start, end, update);
  59366. return this;
  59367. };
  59368. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59369. this._halfroll = this._roll * 0.5;
  59370. this._halfpitch = this._pitch * 0.5;
  59371. this._halfyaw = this._yaw * 0.5;
  59372. this._sinRoll = Math.sin(this._halfroll);
  59373. this._cosRoll = Math.cos(this._halfroll);
  59374. this._sinPitch = Math.sin(this._halfpitch);
  59375. this._cosPitch = Math.cos(this._halfpitch);
  59376. this._sinYaw = Math.sin(this._halfyaw);
  59377. this._cosYaw = Math.cos(this._halfyaw);
  59378. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59379. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59380. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59381. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59382. };
  59383. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59384. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59385. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59386. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59387. this._rotMatrix.m[3] = 0;
  59388. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59389. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59390. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59391. this._rotMatrix.m[7] = 0;
  59392. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59393. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59394. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59395. this._rotMatrix.m[11] = 0;
  59396. this._rotMatrix.m[12] = 0;
  59397. this._rotMatrix.m[13] = 0;
  59398. this._rotMatrix.m[14] = 0;
  59399. this._rotMatrix.m[15] = 1.0;
  59400. };
  59401. /**
  59402. * Disposes the SPS.
  59403. */
  59404. SolidParticleSystem.prototype.dispose = function () {
  59405. this.mesh.dispose();
  59406. this.vars = null;
  59407. // drop references to internal big arrays for the GC
  59408. this._positions = null;
  59409. this._indices = null;
  59410. this._normals = null;
  59411. this._uvs = null;
  59412. this._colors = null;
  59413. this._indices32 = null;
  59414. this._positions32 = null;
  59415. this._normals32 = null;
  59416. this._fixedNormal32 = null;
  59417. this._uvs32 = null;
  59418. this._colors32 = null;
  59419. this.pickedParticles = null;
  59420. };
  59421. /**
  59422. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59423. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59424. * @returns the SPS.
  59425. */
  59426. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59427. if (!this._isVisibilityBoxLocked) {
  59428. this.mesh.refreshBoundingInfo();
  59429. }
  59430. return this;
  59431. };
  59432. /**
  59433. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59434. * @param size the size (float) of the visibility box
  59435. * note : this doesn't lock the SPS mesh bounding box.
  59436. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59437. */
  59438. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59439. var vis = size / 2;
  59440. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59441. };
  59442. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59443. /**
  59444. * Gets whether the SPS as always visible or not
  59445. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59446. */
  59447. get: function () {
  59448. return this._alwaysVisible;
  59449. },
  59450. /**
  59451. * Sets the SPS as always visible or not
  59452. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59453. */
  59454. set: function (val) {
  59455. this._alwaysVisible = val;
  59456. this.mesh.alwaysSelectAsActiveMesh = val;
  59457. },
  59458. enumerable: true,
  59459. configurable: true
  59460. });
  59461. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59462. /**
  59463. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59464. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59465. */
  59466. get: function () {
  59467. return this._isVisibilityBoxLocked;
  59468. },
  59469. /**
  59470. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59471. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59472. */
  59473. set: function (val) {
  59474. this._isVisibilityBoxLocked = val;
  59475. var boundingInfo = this.mesh.getBoundingInfo();
  59476. boundingInfo.isLocked = val;
  59477. },
  59478. enumerable: true,
  59479. configurable: true
  59480. });
  59481. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59482. /**
  59483. * Gets if `setParticles()` computes the particle rotations or not.
  59484. * Default value : true. The SPS is faster when it's set to false.
  59485. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59486. */
  59487. get: function () {
  59488. return this._computeParticleRotation;
  59489. },
  59490. /**
  59491. * Tells to `setParticles()` to compute the particle rotations or not.
  59492. * Default value : true. The SPS is faster when it's set to false.
  59493. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59494. */
  59495. set: function (val) {
  59496. this._computeParticleRotation = val;
  59497. },
  59498. enumerable: true,
  59499. configurable: true
  59500. });
  59501. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59502. /**
  59503. * Gets if `setParticles()` computes the particle colors or not.
  59504. * Default value : true. The SPS is faster when it's set to false.
  59505. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59506. */
  59507. get: function () {
  59508. return this._computeParticleColor;
  59509. },
  59510. /**
  59511. * Tells to `setParticles()` to compute the particle colors or not.
  59512. * Default value : true. The SPS is faster when it's set to false.
  59513. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59514. */
  59515. set: function (val) {
  59516. this._computeParticleColor = val;
  59517. },
  59518. enumerable: true,
  59519. configurable: true
  59520. });
  59521. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59522. /**
  59523. * Gets if `setParticles()` computes the particle textures or not.
  59524. * Default value : true. The SPS is faster when it's set to false.
  59525. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59526. */
  59527. get: function () {
  59528. return this._computeParticleTexture;
  59529. },
  59530. set: function (val) {
  59531. this._computeParticleTexture = val;
  59532. },
  59533. enumerable: true,
  59534. configurable: true
  59535. });
  59536. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59537. /**
  59538. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59539. * Default value : false. The SPS is faster when it's set to false.
  59540. * Note : the particle custom vertex positions aren't stored values.
  59541. */
  59542. get: function () {
  59543. return this._computeParticleVertex;
  59544. },
  59545. /**
  59546. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59547. * Default value : false. The SPS is faster when it's set to false.
  59548. * Note : the particle custom vertex positions aren't stored values.
  59549. */
  59550. set: function (val) {
  59551. this._computeParticleVertex = val;
  59552. },
  59553. enumerable: true,
  59554. configurable: true
  59555. });
  59556. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59557. /**
  59558. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59559. */
  59560. get: function () {
  59561. return this._computeBoundingBox;
  59562. },
  59563. /**
  59564. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59565. */
  59566. set: function (val) {
  59567. this._computeBoundingBox = val;
  59568. },
  59569. enumerable: true,
  59570. configurable: true
  59571. });
  59572. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59573. /**
  59574. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59575. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59576. * Default : `true`
  59577. */
  59578. get: function () {
  59579. return this._depthSortParticles;
  59580. },
  59581. /**
  59582. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59583. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59584. * Default : `true`
  59585. */
  59586. set: function (val) {
  59587. this._depthSortParticles = val;
  59588. },
  59589. enumerable: true,
  59590. configurable: true
  59591. });
  59592. // =======================================================================
  59593. // Particle behavior logic
  59594. // these following methods may be overwritten by the user to fit his needs
  59595. /**
  59596. * This function does nothing. It may be overwritten to set all the particle first values.
  59597. * The SPS doesn't call this function, you may have to call it by your own.
  59598. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59599. */
  59600. SolidParticleSystem.prototype.initParticles = function () {
  59601. };
  59602. /**
  59603. * This function does nothing. It may be overwritten to recycle a particle.
  59604. * The SPS doesn't call this function, you may have to call it by your own.
  59605. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59606. * @param particle The particle to recycle
  59607. * @returns the recycled particle
  59608. */
  59609. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59610. return particle;
  59611. };
  59612. /**
  59613. * Updates a particle : this function should be overwritten by the user.
  59614. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59615. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59616. * @example : just set a particle position or velocity and recycle conditions
  59617. * @param particle The particle to update
  59618. * @returns the updated particle
  59619. */
  59620. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59621. return particle;
  59622. };
  59623. /**
  59624. * Updates a vertex of a particle : it can be overwritten by the user.
  59625. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59626. * @param particle the current particle
  59627. * @param vertex the current index of the current particle
  59628. * @param pt the index of the current vertex in the particle shape
  59629. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59630. * @example : just set a vertex particle position
  59631. * @returns the updated vertex
  59632. */
  59633. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59634. return vertex;
  59635. };
  59636. /**
  59637. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59638. * This does nothing and may be overwritten by the user.
  59639. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59640. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59641. * @param update the boolean update value actually passed to setParticles()
  59642. */
  59643. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59644. };
  59645. /**
  59646. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59647. * This will be passed three parameters.
  59648. * This does nothing and may be overwritten by the user.
  59649. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59650. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59651. * @param update the boolean update value actually passed to setParticles()
  59652. */
  59653. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59654. };
  59655. return SolidParticleSystem;
  59656. }());
  59657. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59658. })(BABYLON || (BABYLON = {}));
  59659. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59660. var BABYLON;
  59661. (function (BABYLON) {
  59662. var ShaderMaterial = /** @class */ (function (_super) {
  59663. __extends(ShaderMaterial, _super);
  59664. function ShaderMaterial(name, scene, shaderPath, options) {
  59665. var _this = _super.call(this, name, scene) || this;
  59666. _this._textures = {};
  59667. _this._textureArrays = {};
  59668. _this._floats = {};
  59669. _this._ints = {};
  59670. _this._floatsArrays = {};
  59671. _this._colors3 = {};
  59672. _this._colors3Arrays = {};
  59673. _this._colors4 = {};
  59674. _this._vectors2 = {};
  59675. _this._vectors3 = {};
  59676. _this._vectors4 = {};
  59677. _this._matrices = {};
  59678. _this._matrices3x3 = {};
  59679. _this._matrices2x2 = {};
  59680. _this._vectors2Arrays = {};
  59681. _this._vectors3Arrays = {};
  59682. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59683. _this._shaderPath = shaderPath;
  59684. options.needAlphaBlending = options.needAlphaBlending || false;
  59685. options.needAlphaTesting = options.needAlphaTesting || false;
  59686. options.attributes = options.attributes || ["position", "normal", "uv"];
  59687. options.uniforms = options.uniforms || ["worldViewProjection"];
  59688. options.uniformBuffers = options.uniformBuffers || [];
  59689. options.samplers = options.samplers || [];
  59690. options.defines = options.defines || [];
  59691. _this._options = options;
  59692. return _this;
  59693. }
  59694. ShaderMaterial.prototype.getClassName = function () {
  59695. return "ShaderMaterial";
  59696. };
  59697. ShaderMaterial.prototype.needAlphaBlending = function () {
  59698. return this._options.needAlphaBlending;
  59699. };
  59700. ShaderMaterial.prototype.needAlphaTesting = function () {
  59701. return this._options.needAlphaTesting;
  59702. };
  59703. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59704. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59705. this._options.uniforms.push(uniformName);
  59706. }
  59707. };
  59708. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59709. if (this._options.samplers.indexOf(name) === -1) {
  59710. this._options.samplers.push(name);
  59711. }
  59712. this._textures[name] = texture;
  59713. return this;
  59714. };
  59715. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59716. if (this._options.samplers.indexOf(name) === -1) {
  59717. this._options.samplers.push(name);
  59718. }
  59719. this._checkUniform(name);
  59720. this._textureArrays[name] = textures;
  59721. return this;
  59722. };
  59723. ShaderMaterial.prototype.setFloat = function (name, value) {
  59724. this._checkUniform(name);
  59725. this._floats[name] = value;
  59726. return this;
  59727. };
  59728. ShaderMaterial.prototype.setInt = function (name, value) {
  59729. this._checkUniform(name);
  59730. this._ints[name] = value;
  59731. return this;
  59732. };
  59733. ShaderMaterial.prototype.setFloats = function (name, value) {
  59734. this._checkUniform(name);
  59735. this._floatsArrays[name] = value;
  59736. return this;
  59737. };
  59738. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59739. this._checkUniform(name);
  59740. this._colors3[name] = value;
  59741. return this;
  59742. };
  59743. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59744. this._checkUniform(name);
  59745. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59746. color.toArray(arr, arr.length);
  59747. return arr;
  59748. }, []);
  59749. return this;
  59750. };
  59751. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59752. this._checkUniform(name);
  59753. this._colors4[name] = value;
  59754. return this;
  59755. };
  59756. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59757. this._checkUniform(name);
  59758. this._vectors2[name] = value;
  59759. return this;
  59760. };
  59761. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59762. this._checkUniform(name);
  59763. this._vectors3[name] = value;
  59764. return this;
  59765. };
  59766. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59767. this._checkUniform(name);
  59768. this._vectors4[name] = value;
  59769. return this;
  59770. };
  59771. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59772. this._checkUniform(name);
  59773. this._matrices[name] = value;
  59774. return this;
  59775. };
  59776. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59777. this._checkUniform(name);
  59778. this._matrices3x3[name] = value;
  59779. return this;
  59780. };
  59781. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59782. this._checkUniform(name);
  59783. this._matrices2x2[name] = value;
  59784. return this;
  59785. };
  59786. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59787. this._checkUniform(name);
  59788. this._vectors2Arrays[name] = value;
  59789. return this;
  59790. };
  59791. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59792. this._checkUniform(name);
  59793. this._vectors3Arrays[name] = value;
  59794. return this;
  59795. };
  59796. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59797. if (!mesh) {
  59798. return true;
  59799. }
  59800. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59801. return false;
  59802. }
  59803. return false;
  59804. };
  59805. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59806. var scene = this.getScene();
  59807. var engine = scene.getEngine();
  59808. if (!this.checkReadyOnEveryCall) {
  59809. if (this._renderId === scene.getRenderId()) {
  59810. if (this._checkCache(scene, mesh, useInstances)) {
  59811. return true;
  59812. }
  59813. }
  59814. }
  59815. // Instances
  59816. var defines = [];
  59817. var attribs = [];
  59818. var fallbacks = new BABYLON.EffectFallbacks();
  59819. if (useInstances) {
  59820. defines.push("#define INSTANCES");
  59821. }
  59822. for (var index = 0; index < this._options.defines.length; index++) {
  59823. defines.push(this._options.defines[index]);
  59824. }
  59825. for (var index = 0; index < this._options.attributes.length; index++) {
  59826. attribs.push(this._options.attributes[index]);
  59827. }
  59828. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59829. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59830. defines.push("#define VERTEXCOLOR");
  59831. }
  59832. // Bones
  59833. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59836. if (mesh.numBoneInfluencers > 4) {
  59837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59839. }
  59840. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59841. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59842. fallbacks.addCPUSkinningFallback(0, mesh);
  59843. if (this._options.uniforms.indexOf("mBones") === -1) {
  59844. this._options.uniforms.push("mBones");
  59845. }
  59846. }
  59847. else {
  59848. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59849. }
  59850. // Textures
  59851. for (var name in this._textures) {
  59852. if (!this._textures[name].isReady()) {
  59853. return false;
  59854. }
  59855. }
  59856. // Alpha test
  59857. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59858. defines.push("#define ALPHATEST");
  59859. }
  59860. var previousEffect = this._effect;
  59861. var join = defines.join("\n");
  59862. this._effect = engine.createEffect(this._shaderPath, {
  59863. attributes: attribs,
  59864. uniformsNames: this._options.uniforms,
  59865. uniformBuffersNames: this._options.uniformBuffers,
  59866. samplers: this._options.samplers,
  59867. defines: join,
  59868. fallbacks: fallbacks,
  59869. onCompiled: this.onCompiled,
  59870. onError: this.onError
  59871. }, engine);
  59872. if (!this._effect.isReady()) {
  59873. return false;
  59874. }
  59875. if (previousEffect !== this._effect) {
  59876. scene.resetCachedMaterial();
  59877. }
  59878. this._renderId = scene.getRenderId();
  59879. return true;
  59880. };
  59881. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59882. var scene = this.getScene();
  59883. if (!this._effect) {
  59884. return;
  59885. }
  59886. if (this._options.uniforms.indexOf("world") !== -1) {
  59887. this._effect.setMatrix("world", world);
  59888. }
  59889. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59890. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59891. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59892. }
  59893. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59894. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59895. }
  59896. };
  59897. ShaderMaterial.prototype.bind = function (world, mesh) {
  59898. // Std values
  59899. this.bindOnlyWorldMatrix(world);
  59900. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59901. if (this._options.uniforms.indexOf("view") !== -1) {
  59902. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59903. }
  59904. if (this._options.uniforms.indexOf("projection") !== -1) {
  59905. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59906. }
  59907. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59908. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59909. }
  59910. // Bones
  59911. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59912. var name;
  59913. // Texture
  59914. for (name in this._textures) {
  59915. this._effect.setTexture(name, this._textures[name]);
  59916. }
  59917. // Texture arrays
  59918. for (name in this._textureArrays) {
  59919. this._effect.setTextureArray(name, this._textureArrays[name]);
  59920. }
  59921. // Int
  59922. for (name in this._ints) {
  59923. this._effect.setInt(name, this._ints[name]);
  59924. }
  59925. // Float
  59926. for (name in this._floats) {
  59927. this._effect.setFloat(name, this._floats[name]);
  59928. }
  59929. // Floats
  59930. for (name in this._floatsArrays) {
  59931. this._effect.setArray(name, this._floatsArrays[name]);
  59932. }
  59933. // Color3
  59934. for (name in this._colors3) {
  59935. this._effect.setColor3(name, this._colors3[name]);
  59936. }
  59937. for (name in this._colors3Arrays) {
  59938. this._effect.setArray3(name, this._colors3Arrays[name]);
  59939. }
  59940. // Color4
  59941. for (name in this._colors4) {
  59942. var color = this._colors4[name];
  59943. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59944. }
  59945. // Vector2
  59946. for (name in this._vectors2) {
  59947. this._effect.setVector2(name, this._vectors2[name]);
  59948. }
  59949. // Vector3
  59950. for (name in this._vectors3) {
  59951. this._effect.setVector3(name, this._vectors3[name]);
  59952. }
  59953. // Vector4
  59954. for (name in this._vectors4) {
  59955. this._effect.setVector4(name, this._vectors4[name]);
  59956. }
  59957. // Matrix
  59958. for (name in this._matrices) {
  59959. this._effect.setMatrix(name, this._matrices[name]);
  59960. }
  59961. // Matrix 3x3
  59962. for (name in this._matrices3x3) {
  59963. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59964. }
  59965. // Matrix 2x2
  59966. for (name in this._matrices2x2) {
  59967. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59968. }
  59969. // Vector2Array
  59970. for (name in this._vectors2Arrays) {
  59971. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59972. }
  59973. // Vector3Array
  59974. for (name in this._vectors3Arrays) {
  59975. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59976. }
  59977. }
  59978. this._afterBind(mesh);
  59979. };
  59980. ShaderMaterial.prototype.getActiveTextures = function () {
  59981. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59982. for (var name in this._textures) {
  59983. activeTextures.push(this._textures[name]);
  59984. }
  59985. for (var name in this._textureArrays) {
  59986. var array = this._textureArrays[name];
  59987. for (var index = 0; index < array.length; index++) {
  59988. activeTextures.push(array[index]);
  59989. }
  59990. }
  59991. return activeTextures;
  59992. };
  59993. ShaderMaterial.prototype.hasTexture = function (texture) {
  59994. if (_super.prototype.hasTexture.call(this, texture)) {
  59995. return true;
  59996. }
  59997. for (var name in this._textures) {
  59998. if (this._textures[name] === texture) {
  59999. return true;
  60000. }
  60001. }
  60002. for (var name in this._textureArrays) {
  60003. var array = this._textureArrays[name];
  60004. for (var index = 0; index < array.length; index++) {
  60005. if (array[index] === texture) {
  60006. return true;
  60007. }
  60008. }
  60009. }
  60010. return false;
  60011. };
  60012. ShaderMaterial.prototype.clone = function (name) {
  60013. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60014. return newShaderMaterial;
  60015. };
  60016. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60017. if (forceDisposeTextures) {
  60018. var name;
  60019. for (name in this._textures) {
  60020. this._textures[name].dispose();
  60021. }
  60022. for (name in this._textureArrays) {
  60023. var array = this._textureArrays[name];
  60024. for (var index = 0; index < array.length; index++) {
  60025. array[index].dispose();
  60026. }
  60027. }
  60028. }
  60029. this._textures = {};
  60030. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60031. };
  60032. ShaderMaterial.prototype.serialize = function () {
  60033. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60034. serializationObject.customType = "BABYLON.ShaderMaterial";
  60035. serializationObject.options = this._options;
  60036. serializationObject.shaderPath = this._shaderPath;
  60037. var name;
  60038. // Texture
  60039. serializationObject.textures = {};
  60040. for (name in this._textures) {
  60041. serializationObject.textures[name] = this._textures[name].serialize();
  60042. }
  60043. // Texture arrays
  60044. serializationObject.textureArrays = {};
  60045. for (name in this._textureArrays) {
  60046. serializationObject.textureArrays[name] = [];
  60047. var array = this._textureArrays[name];
  60048. for (var index = 0; index < array.length; index++) {
  60049. serializationObject.textureArrays[name].push(array[index].serialize());
  60050. }
  60051. }
  60052. // Float
  60053. serializationObject.floats = {};
  60054. for (name in this._floats) {
  60055. serializationObject.floats[name] = this._floats[name];
  60056. }
  60057. // Float s
  60058. serializationObject.FloatArrays = {};
  60059. for (name in this._floatsArrays) {
  60060. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60061. }
  60062. // Color3
  60063. serializationObject.colors3 = {};
  60064. for (name in this._colors3) {
  60065. serializationObject.colors3[name] = this._colors3[name].asArray();
  60066. }
  60067. // Color3 array
  60068. serializationObject.colors3Arrays = {};
  60069. for (name in this._colors3Arrays) {
  60070. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60071. }
  60072. // Color4
  60073. serializationObject.colors4 = {};
  60074. for (name in this._colors4) {
  60075. serializationObject.colors4[name] = this._colors4[name].asArray();
  60076. }
  60077. // Vector2
  60078. serializationObject.vectors2 = {};
  60079. for (name in this._vectors2) {
  60080. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60081. }
  60082. // Vector3
  60083. serializationObject.vectors3 = {};
  60084. for (name in this._vectors3) {
  60085. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60086. }
  60087. // Vector4
  60088. serializationObject.vectors4 = {};
  60089. for (name in this._vectors4) {
  60090. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60091. }
  60092. // Matrix
  60093. serializationObject.matrices = {};
  60094. for (name in this._matrices) {
  60095. serializationObject.matrices[name] = this._matrices[name].asArray();
  60096. }
  60097. // Matrix 3x3
  60098. serializationObject.matrices3x3 = {};
  60099. for (name in this._matrices3x3) {
  60100. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60101. }
  60102. // Matrix 2x2
  60103. serializationObject.matrices2x2 = {};
  60104. for (name in this._matrices2x2) {
  60105. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60106. }
  60107. // Vector2Array
  60108. serializationObject.vectors2Arrays = {};
  60109. for (name in this._vectors2Arrays) {
  60110. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60111. }
  60112. // Vector3Array
  60113. serializationObject.vectors3Arrays = {};
  60114. for (name in this._vectors3Arrays) {
  60115. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60116. }
  60117. return serializationObject;
  60118. };
  60119. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60120. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60121. var name;
  60122. // Texture
  60123. for (name in source.textures) {
  60124. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60125. }
  60126. // Texture arrays
  60127. for (name in source.textureArrays) {
  60128. var array = source.textureArrays[name];
  60129. var textureArray = new Array();
  60130. for (var index = 0; index < array.length; index++) {
  60131. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60132. }
  60133. material.setTextureArray(name, textureArray);
  60134. }
  60135. // Float
  60136. for (name in source.floats) {
  60137. material.setFloat(name, source.floats[name]);
  60138. }
  60139. // Float s
  60140. for (name in source.floatsArrays) {
  60141. material.setFloats(name, source.floatsArrays[name]);
  60142. }
  60143. // Color3
  60144. for (name in source.colors3) {
  60145. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60146. }
  60147. // Color3 arrays
  60148. for (name in source.colors3Arrays) {
  60149. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60150. if (i % 3 === 0) {
  60151. arr.push([num]);
  60152. }
  60153. else {
  60154. arr[arr.length - 1].push(num);
  60155. }
  60156. return arr;
  60157. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60158. material.setColor3Array(name, colors);
  60159. }
  60160. // Color4
  60161. for (name in source.colors4) {
  60162. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60163. }
  60164. // Vector2
  60165. for (name in source.vectors2) {
  60166. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60167. }
  60168. // Vector3
  60169. for (name in source.vectors3) {
  60170. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60171. }
  60172. // Vector4
  60173. for (name in source.vectors4) {
  60174. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60175. }
  60176. // Matrix
  60177. for (name in source.matrices) {
  60178. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60179. }
  60180. // Matrix 3x3
  60181. for (name in source.matrices3x3) {
  60182. material.setMatrix3x3(name, source.matrices3x3[name]);
  60183. }
  60184. // Matrix 2x2
  60185. for (name in source.matrices2x2) {
  60186. material.setMatrix2x2(name, source.matrices2x2[name]);
  60187. }
  60188. // Vector2Array
  60189. for (name in source.vectors2Arrays) {
  60190. material.setArray2(name, source.vectors2Arrays[name]);
  60191. }
  60192. // Vector3Array
  60193. for (name in source.vectors3Arrays) {
  60194. material.setArray3(name, source.vectors3Arrays[name]);
  60195. }
  60196. return material;
  60197. };
  60198. return ShaderMaterial;
  60199. }(BABYLON.Material));
  60200. BABYLON.ShaderMaterial = ShaderMaterial;
  60201. })(BABYLON || (BABYLON = {}));
  60202. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60203. var BABYLON;
  60204. (function (BABYLON) {
  60205. var GroundMesh = /** @class */ (function (_super) {
  60206. __extends(GroundMesh, _super);
  60207. function GroundMesh(name, scene) {
  60208. var _this = _super.call(this, name, scene) || this;
  60209. _this.generateOctree = false;
  60210. return _this;
  60211. }
  60212. GroundMesh.prototype.getClassName = function () {
  60213. return "GroundMesh";
  60214. };
  60215. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60216. get: function () {
  60217. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60218. },
  60219. enumerable: true,
  60220. configurable: true
  60221. });
  60222. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60223. get: function () {
  60224. return this._subdivisionsX;
  60225. },
  60226. enumerable: true,
  60227. configurable: true
  60228. });
  60229. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60230. get: function () {
  60231. return this._subdivisionsY;
  60232. },
  60233. enumerable: true,
  60234. configurable: true
  60235. });
  60236. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60237. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60238. this._subdivisionsX = chunksCount;
  60239. this._subdivisionsY = chunksCount;
  60240. this.subdivide(chunksCount);
  60241. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60242. };
  60243. /**
  60244. * Returns a height (y) value in the Worl system :
  60245. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60246. * Returns the ground y position if (x, z) are outside the ground surface.
  60247. */
  60248. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60249. var world = this.getWorldMatrix();
  60250. var invMat = BABYLON.Tmp.Matrix[5];
  60251. world.invertToRef(invMat);
  60252. var tmpVect = BABYLON.Tmp.Vector3[8];
  60253. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60254. x = tmpVect.x;
  60255. z = tmpVect.z;
  60256. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60257. return this.position.y;
  60258. }
  60259. if (!this._heightQuads || this._heightQuads.length == 0) {
  60260. this._initHeightQuads();
  60261. this._computeHeightQuads();
  60262. }
  60263. var facet = this._getFacetAt(x, z);
  60264. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60265. // return y in the World system
  60266. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60267. return tmpVect.y;
  60268. };
  60269. /**
  60270. * Returns a normalized vector (Vector3) orthogonal to the ground
  60271. * at the ground coordinates (x, z) expressed in the World system.
  60272. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60273. */
  60274. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60275. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60276. this.getNormalAtCoordinatesToRef(x, z, normal);
  60277. return normal;
  60278. };
  60279. /**
  60280. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60281. * at the ground coordinates (x, z) expressed in the World system.
  60282. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60283. * Returns the GroundMesh.
  60284. */
  60285. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60286. var world = this.getWorldMatrix();
  60287. var tmpMat = BABYLON.Tmp.Matrix[5];
  60288. world.invertToRef(tmpMat);
  60289. var tmpVect = BABYLON.Tmp.Vector3[8];
  60290. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60291. x = tmpVect.x;
  60292. z = tmpVect.z;
  60293. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60294. return this;
  60295. }
  60296. if (!this._heightQuads || this._heightQuads.length == 0) {
  60297. this._initHeightQuads();
  60298. this._computeHeightQuads();
  60299. }
  60300. var facet = this._getFacetAt(x, z);
  60301. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60302. return this;
  60303. };
  60304. /**
  60305. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60306. * if the ground has been updated.
  60307. * This can be used in the render loop.
  60308. * Returns the GroundMesh.
  60309. */
  60310. GroundMesh.prototype.updateCoordinateHeights = function () {
  60311. if (!this._heightQuads || this._heightQuads.length == 0) {
  60312. this._initHeightQuads();
  60313. }
  60314. this._computeHeightQuads();
  60315. return this;
  60316. };
  60317. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60318. GroundMesh.prototype._getFacetAt = function (x, z) {
  60319. // retrieve col and row from x, z coordinates in the ground local system
  60320. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60321. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60322. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60323. var facet;
  60324. if (z < quad.slope.x * x + quad.slope.y) {
  60325. facet = quad.facet1;
  60326. }
  60327. else {
  60328. facet = quad.facet2;
  60329. }
  60330. return facet;
  60331. };
  60332. // Creates and populates the heightMap array with "facet" elements :
  60333. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60334. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60335. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60336. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60337. // Returns the GroundMesh.
  60338. GroundMesh.prototype._initHeightQuads = function () {
  60339. var subdivisionsX = this._subdivisionsX;
  60340. var subdivisionsY = this._subdivisionsY;
  60341. this._heightQuads = new Array();
  60342. for (var row = 0; row < subdivisionsY; row++) {
  60343. for (var col = 0; col < subdivisionsX; col++) {
  60344. 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) };
  60345. this._heightQuads[row * subdivisionsX + col] = quad;
  60346. }
  60347. }
  60348. return this;
  60349. };
  60350. // Compute each quad element values and update the the heightMap array :
  60351. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60352. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60353. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60354. // Returns the GroundMesh.
  60355. GroundMesh.prototype._computeHeightQuads = function () {
  60356. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60357. if (!positions) {
  60358. return this;
  60359. }
  60360. var v1 = BABYLON.Tmp.Vector3[3];
  60361. var v2 = BABYLON.Tmp.Vector3[2];
  60362. var v3 = BABYLON.Tmp.Vector3[1];
  60363. var v4 = BABYLON.Tmp.Vector3[0];
  60364. var v1v2 = BABYLON.Tmp.Vector3[4];
  60365. var v1v3 = BABYLON.Tmp.Vector3[5];
  60366. var v1v4 = BABYLON.Tmp.Vector3[6];
  60367. var norm1 = BABYLON.Tmp.Vector3[7];
  60368. var norm2 = BABYLON.Tmp.Vector3[8];
  60369. var i = 0;
  60370. var j = 0;
  60371. var k = 0;
  60372. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60373. var h = 0;
  60374. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60375. var d2 = 0;
  60376. var subdivisionsX = this._subdivisionsX;
  60377. var subdivisionsY = this._subdivisionsY;
  60378. for (var row = 0; row < subdivisionsY; row++) {
  60379. for (var col = 0; col < subdivisionsX; col++) {
  60380. i = col * 3;
  60381. j = row * (subdivisionsX + 1) * 3;
  60382. k = (row + 1) * (subdivisionsX + 1) * 3;
  60383. v1.x = positions[j + i];
  60384. v1.y = positions[j + i + 1];
  60385. v1.z = positions[j + i + 2];
  60386. v2.x = positions[j + i + 3];
  60387. v2.y = positions[j + i + 4];
  60388. v2.z = positions[j + i + 5];
  60389. v3.x = positions[k + i];
  60390. v3.y = positions[k + i + 1];
  60391. v3.z = positions[k + i + 2];
  60392. v4.x = positions[k + i + 3];
  60393. v4.y = positions[k + i + 4];
  60394. v4.z = positions[k + i + 5];
  60395. // 2D slope V1V4
  60396. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60397. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60398. // facet equations :
  60399. // we compute each facet normal vector
  60400. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60401. // we compute the value d by applying the equation to v1 which belongs to the plane
  60402. // then we store the facet equation in a Vector4
  60403. v2.subtractToRef(v1, v1v2);
  60404. v3.subtractToRef(v1, v1v3);
  60405. v4.subtractToRef(v1, v1v4);
  60406. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60407. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60408. norm1.normalize();
  60409. norm2.normalize();
  60410. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60411. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60412. var quad = this._heightQuads[row * subdivisionsX + col];
  60413. quad.slope.copyFromFloats(cd, h);
  60414. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60415. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60416. }
  60417. }
  60418. return this;
  60419. };
  60420. GroundMesh.prototype.serialize = function (serializationObject) {
  60421. _super.prototype.serialize.call(this, serializationObject);
  60422. serializationObject.subdivisionsX = this._subdivisionsX;
  60423. serializationObject.subdivisionsY = this._subdivisionsY;
  60424. serializationObject.minX = this._minX;
  60425. serializationObject.maxX = this._maxX;
  60426. serializationObject.minZ = this._minZ;
  60427. serializationObject.maxZ = this._maxZ;
  60428. serializationObject.width = this._width;
  60429. serializationObject.height = this._height;
  60430. };
  60431. GroundMesh.Parse = function (parsedMesh, scene) {
  60432. var result = new GroundMesh(parsedMesh.name, scene);
  60433. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60434. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60435. result._minX = parsedMesh.minX;
  60436. result._maxX = parsedMesh.maxX;
  60437. result._minZ = parsedMesh.minZ;
  60438. result._maxZ = parsedMesh.maxZ;
  60439. result._width = parsedMesh.width;
  60440. result._height = parsedMesh.height;
  60441. return result;
  60442. };
  60443. return GroundMesh;
  60444. }(BABYLON.Mesh));
  60445. BABYLON.GroundMesh = GroundMesh;
  60446. })(BABYLON || (BABYLON = {}));
  60447. //# sourceMappingURL=babylon.groundMesh.js.map
  60448. var BABYLON;
  60449. (function (BABYLON) {
  60450. /**
  60451. * Creates an instance based on a source mesh.
  60452. */
  60453. var InstancedMesh = /** @class */ (function (_super) {
  60454. __extends(InstancedMesh, _super);
  60455. function InstancedMesh(name, source) {
  60456. var _this = _super.call(this, name, source.getScene()) || this;
  60457. source.instances.push(_this);
  60458. _this._sourceMesh = source;
  60459. _this.position.copyFrom(source.position);
  60460. _this.rotation.copyFrom(source.rotation);
  60461. _this.scaling.copyFrom(source.scaling);
  60462. if (source.rotationQuaternion) {
  60463. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60464. }
  60465. _this.infiniteDistance = source.infiniteDistance;
  60466. _this.setPivotMatrix(source.getPivotMatrix());
  60467. _this.refreshBoundingInfo();
  60468. _this._syncSubMeshes();
  60469. return _this;
  60470. }
  60471. /**
  60472. * Returns the string "InstancedMesh".
  60473. */
  60474. InstancedMesh.prototype.getClassName = function () {
  60475. return "InstancedMesh";
  60476. };
  60477. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60478. // Methods
  60479. get: function () {
  60480. return this._sourceMesh.receiveShadows;
  60481. },
  60482. enumerable: true,
  60483. configurable: true
  60484. });
  60485. Object.defineProperty(InstancedMesh.prototype, "material", {
  60486. get: function () {
  60487. return this._sourceMesh.material;
  60488. },
  60489. enumerable: true,
  60490. configurable: true
  60491. });
  60492. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60493. get: function () {
  60494. return this._sourceMesh.visibility;
  60495. },
  60496. enumerable: true,
  60497. configurable: true
  60498. });
  60499. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60500. get: function () {
  60501. return this._sourceMesh.skeleton;
  60502. },
  60503. enumerable: true,
  60504. configurable: true
  60505. });
  60506. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60507. get: function () {
  60508. return this._sourceMesh.renderingGroupId;
  60509. },
  60510. set: function (value) {
  60511. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60512. return;
  60513. }
  60514. //no-op with warning
  60515. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60516. },
  60517. enumerable: true,
  60518. configurable: true
  60519. });
  60520. /**
  60521. * Returns the total number of vertices (integer).
  60522. */
  60523. InstancedMesh.prototype.getTotalVertices = function () {
  60524. return this._sourceMesh.getTotalVertices();
  60525. };
  60526. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60527. get: function () {
  60528. return this._sourceMesh;
  60529. },
  60530. enumerable: true,
  60531. configurable: true
  60532. });
  60533. /**
  60534. * Is this node ready to be used/rendered
  60535. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60536. * @return {boolean} is it ready
  60537. */
  60538. InstancedMesh.prototype.isReady = function (completeCheck) {
  60539. if (completeCheck === void 0) { completeCheck = false; }
  60540. return this._sourceMesh.isReady(completeCheck, true);
  60541. };
  60542. /**
  60543. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60544. */
  60545. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60546. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60547. };
  60548. /**
  60549. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60550. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60551. * The `data` are either a numeric array either a Float32Array.
  60552. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60553. * 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).
  60554. * Note that a new underlying VertexBuffer object is created each call.
  60555. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60556. *
  60557. * Possible `kind` values :
  60558. * - BABYLON.VertexBuffer.PositionKind
  60559. * - BABYLON.VertexBuffer.UVKind
  60560. * - BABYLON.VertexBuffer.UV2Kind
  60561. * - BABYLON.VertexBuffer.UV3Kind
  60562. * - BABYLON.VertexBuffer.UV4Kind
  60563. * - BABYLON.VertexBuffer.UV5Kind
  60564. * - BABYLON.VertexBuffer.UV6Kind
  60565. * - BABYLON.VertexBuffer.ColorKind
  60566. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60567. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60568. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60569. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60570. *
  60571. * Returns the Mesh.
  60572. */
  60573. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60574. if (this.sourceMesh) {
  60575. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60576. }
  60577. return this.sourceMesh;
  60578. };
  60579. /**
  60580. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60581. * If the mesh has no geometry, it is simply returned as it is.
  60582. * The `data` are either a numeric array either a Float32Array.
  60583. * No new underlying VertexBuffer object is created.
  60584. * 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.
  60585. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60586. *
  60587. * Possible `kind` values :
  60588. * - BABYLON.VertexBuffer.PositionKind
  60589. * - BABYLON.VertexBuffer.UVKind
  60590. * - BABYLON.VertexBuffer.UV2Kind
  60591. * - BABYLON.VertexBuffer.UV3Kind
  60592. * - BABYLON.VertexBuffer.UV4Kind
  60593. * - BABYLON.VertexBuffer.UV5Kind
  60594. * - BABYLON.VertexBuffer.UV6Kind
  60595. * - BABYLON.VertexBuffer.ColorKind
  60596. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60597. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60598. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60599. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60600. *
  60601. * Returns the Mesh.
  60602. */
  60603. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60604. if (this.sourceMesh) {
  60605. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60606. }
  60607. return this.sourceMesh;
  60608. };
  60609. /**
  60610. * Sets the mesh indices.
  60611. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60612. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60613. * This method creates a new index buffer each call.
  60614. * Returns the Mesh.
  60615. */
  60616. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60617. if (totalVertices === void 0) { totalVertices = null; }
  60618. if (this.sourceMesh) {
  60619. this.sourceMesh.setIndices(indices, totalVertices);
  60620. }
  60621. return this.sourceMesh;
  60622. };
  60623. /**
  60624. * Boolean : True if the mesh owns the requested kind of data.
  60625. */
  60626. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60627. return this._sourceMesh.isVerticesDataPresent(kind);
  60628. };
  60629. /**
  60630. * Returns an array of indices (IndicesArray).
  60631. */
  60632. InstancedMesh.prototype.getIndices = function () {
  60633. return this._sourceMesh.getIndices();
  60634. };
  60635. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60636. get: function () {
  60637. return this._sourceMesh._positions;
  60638. },
  60639. enumerable: true,
  60640. configurable: true
  60641. });
  60642. /**
  60643. * Sets a new updated BoundingInfo to the mesh.
  60644. * Returns the mesh.
  60645. */
  60646. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60647. var meshBB = this._sourceMesh.getBoundingInfo();
  60648. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60649. this._updateBoundingInfo();
  60650. return this;
  60651. };
  60652. InstancedMesh.prototype._preActivate = function () {
  60653. if (this._currentLOD) {
  60654. this._currentLOD._preActivate();
  60655. }
  60656. return this;
  60657. };
  60658. InstancedMesh.prototype._activate = function (renderId) {
  60659. if (this._currentLOD) {
  60660. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60661. }
  60662. return this;
  60663. };
  60664. /**
  60665. * Returns the current associated LOD AbstractMesh.
  60666. */
  60667. InstancedMesh.prototype.getLOD = function (camera) {
  60668. if (!camera) {
  60669. return this;
  60670. }
  60671. var boundingInfo = this.getBoundingInfo();
  60672. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60673. if (this._currentLOD === this.sourceMesh) {
  60674. return this;
  60675. }
  60676. return this._currentLOD;
  60677. };
  60678. InstancedMesh.prototype._syncSubMeshes = function () {
  60679. this.releaseSubMeshes();
  60680. if (this._sourceMesh.subMeshes) {
  60681. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60682. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60683. }
  60684. }
  60685. return this;
  60686. };
  60687. InstancedMesh.prototype._generatePointsArray = function () {
  60688. return this._sourceMesh._generatePointsArray();
  60689. };
  60690. /**
  60691. * Creates a new InstancedMesh from the current mesh.
  60692. * - name (string) : the cloned mesh name
  60693. * - newParent (optional Node) : the optional Node to parent the clone to.
  60694. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60695. *
  60696. * Returns the clone.
  60697. */
  60698. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60699. var result = this._sourceMesh.createInstance(name);
  60700. // Deep copy
  60701. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60702. // Bounding info
  60703. this.refreshBoundingInfo();
  60704. // Parent
  60705. if (newParent) {
  60706. result.parent = newParent;
  60707. }
  60708. if (!doNotCloneChildren) {
  60709. // Children
  60710. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60711. var mesh = this.getScene().meshes[index];
  60712. if (mesh.parent === this) {
  60713. mesh.clone(mesh.name, result);
  60714. }
  60715. }
  60716. }
  60717. result.computeWorldMatrix(true);
  60718. return result;
  60719. };
  60720. /**
  60721. * Disposes the InstancedMesh.
  60722. * Returns nothing.
  60723. */
  60724. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60725. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60726. // Remove from mesh
  60727. var index = this._sourceMesh.instances.indexOf(this);
  60728. this._sourceMesh.instances.splice(index, 1);
  60729. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60730. };
  60731. return InstancedMesh;
  60732. }(BABYLON.AbstractMesh));
  60733. BABYLON.InstancedMesh = InstancedMesh;
  60734. })(BABYLON || (BABYLON = {}));
  60735. //# sourceMappingURL=babylon.instancedMesh.js.map
  60736. var BABYLON;
  60737. (function (BABYLON) {
  60738. var LinesMesh = /** @class */ (function (_super) {
  60739. __extends(LinesMesh, _super);
  60740. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60741. if (scene === void 0) { scene = null; }
  60742. if (parent === void 0) { parent = null; }
  60743. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60744. _this.useVertexColor = useVertexColor;
  60745. _this.useVertexAlpha = useVertexAlpha;
  60746. _this.color = new BABYLON.Color3(1, 1, 1);
  60747. _this.alpha = 1;
  60748. if (source) {
  60749. _this.color = source.color.clone();
  60750. _this.alpha = source.alpha;
  60751. _this.useVertexColor = source.useVertexColor;
  60752. _this.useVertexAlpha = source.useVertexAlpha;
  60753. }
  60754. _this._intersectionThreshold = 0.1;
  60755. var defines = [];
  60756. var options = {
  60757. attributes: [BABYLON.VertexBuffer.PositionKind],
  60758. uniforms: ["world", "viewProjection"],
  60759. needAlphaBlending: true,
  60760. defines: defines
  60761. };
  60762. if (useVertexAlpha === false) {
  60763. options.needAlphaBlending = false;
  60764. }
  60765. if (!useVertexColor) {
  60766. options.uniforms.push("color");
  60767. }
  60768. else {
  60769. options.defines.push("#define VERTEXCOLOR");
  60770. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60771. }
  60772. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60773. return _this;
  60774. }
  60775. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60776. /**
  60777. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60778. * This margin is expressed in world space coordinates, so its value may vary.
  60779. * Default value is 0.1
  60780. * @returns the intersection Threshold value.
  60781. */
  60782. get: function () {
  60783. return this._intersectionThreshold;
  60784. },
  60785. /**
  60786. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60787. * This margin is expressed in world space coordinates, so its value may vary.
  60788. * @param value the new threshold to apply
  60789. */
  60790. set: function (value) {
  60791. if (this._intersectionThreshold === value) {
  60792. return;
  60793. }
  60794. this._intersectionThreshold = value;
  60795. if (this.geometry) {
  60796. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60797. }
  60798. },
  60799. enumerable: true,
  60800. configurable: true
  60801. });
  60802. /**
  60803. * Returns the string "LineMesh"
  60804. */
  60805. LinesMesh.prototype.getClassName = function () {
  60806. return "LinesMesh";
  60807. };
  60808. Object.defineProperty(LinesMesh.prototype, "material", {
  60809. get: function () {
  60810. return this._colorShader;
  60811. },
  60812. set: function (value) {
  60813. // Do nothing
  60814. },
  60815. enumerable: true,
  60816. configurable: true
  60817. });
  60818. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60819. get: function () {
  60820. return false;
  60821. },
  60822. enumerable: true,
  60823. configurable: true
  60824. });
  60825. LinesMesh.prototype.createInstance = function (name) {
  60826. throw new Error("LinesMeshes do not support createInstance.");
  60827. };
  60828. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60829. if (!this._geometry) {
  60830. return this;
  60831. }
  60832. // VBOs
  60833. this._geometry._bind(this._colorShader.getEffect());
  60834. // Color
  60835. if (!this.useVertexColor) {
  60836. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60837. }
  60838. return this;
  60839. };
  60840. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60841. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60842. return this;
  60843. }
  60844. var engine = this.getScene().getEngine();
  60845. // Draw order
  60846. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60847. return this;
  60848. };
  60849. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60850. this._colorShader.dispose();
  60851. _super.prototype.dispose.call(this, doNotRecurse);
  60852. };
  60853. /**
  60854. * Returns a new LineMesh object cloned from the current one.
  60855. */
  60856. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60857. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60858. };
  60859. return LinesMesh;
  60860. }(BABYLON.Mesh));
  60861. BABYLON.LinesMesh = LinesMesh;
  60862. })(BABYLON || (BABYLON = {}));
  60863. //# sourceMappingURL=babylon.linesMesh.js.map
  60864. var BABYLON;
  60865. (function (BABYLON) {
  60866. /**
  60867. * Class containing static functions to help procedurally build meshes
  60868. */
  60869. var MeshBuilder = /** @class */ (function () {
  60870. function MeshBuilder() {
  60871. }
  60872. MeshBuilder.updateSideOrientation = function (orientation) {
  60873. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60874. return BABYLON.Mesh.DOUBLESIDE;
  60875. }
  60876. if (orientation === undefined || orientation === null) {
  60877. return BABYLON.Mesh.FRONTSIDE;
  60878. }
  60879. return orientation;
  60880. };
  60881. /**
  60882. * Creates a box mesh
  60883. * * The parameter `size` sets the size (float) of each box side (default 1)
  60884. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60885. * * 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)
  60886. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60887. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60888. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60889. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60890. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60891. * @param name defines the name of the mesh
  60892. * @param options defines the options used to create the mesh
  60893. * @param scene defines the hosting scene
  60894. * @returns the box mesh
  60895. */
  60896. MeshBuilder.CreateBox = function (name, options, scene) {
  60897. if (scene === void 0) { scene = null; }
  60898. var box = new BABYLON.Mesh(name, scene);
  60899. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60900. box._originalBuilderSideOrientation = options.sideOrientation;
  60901. var vertexData = BABYLON.VertexData.CreateBox(options);
  60902. vertexData.applyToMesh(box, options.updatable);
  60903. return box;
  60904. };
  60905. /**
  60906. * Creates a sphere mesh
  60907. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60908. * * 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`)
  60909. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60910. * * 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
  60911. * * 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)
  60912. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60913. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60914. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60915. * @param name defines the name of the mesh
  60916. * @param options defines the options used to create the mesh
  60917. * @param scene defines the hosting scene
  60918. * @returns the sphere mesh
  60919. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60920. */
  60921. MeshBuilder.CreateSphere = function (name, options, scene) {
  60922. var sphere = new BABYLON.Mesh(name, scene);
  60923. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60924. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60925. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60926. vertexData.applyToMesh(sphere, options.updatable);
  60927. return sphere;
  60928. };
  60929. /**
  60930. * Creates a plane polygonal mesh. By default, this is a disc
  60931. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60932. * * 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
  60933. * * 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
  60934. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60935. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60936. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60937. * @param name defines the name of the mesh
  60938. * @param options defines the options used to create the mesh
  60939. * @param scene defines the hosting scene
  60940. * @returns the plane polygonal mesh
  60941. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60942. */
  60943. MeshBuilder.CreateDisc = function (name, options, scene) {
  60944. if (scene === void 0) { scene = null; }
  60945. var disc = new BABYLON.Mesh(name, scene);
  60946. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60947. disc._originalBuilderSideOrientation = options.sideOrientation;
  60948. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60949. vertexData.applyToMesh(disc, options.updatable);
  60950. return disc;
  60951. };
  60952. /**
  60953. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60954. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60955. * * 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`)
  60956. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60957. * * 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
  60958. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60959. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60960. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60961. * @param name defines the name of the mesh
  60962. * @param options defines the options used to create the mesh
  60963. * @param scene defines the hosting scene
  60964. * @returns the icosahedron mesh
  60965. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60966. */
  60967. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60968. var sphere = new BABYLON.Mesh(name, scene);
  60969. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60970. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60971. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60972. vertexData.applyToMesh(sphere, options.updatable);
  60973. return sphere;
  60974. };
  60975. ;
  60976. /**
  60977. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60978. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60979. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60980. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60981. * * 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
  60982. * * 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
  60983. * * 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
  60984. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60985. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60986. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60987. * * 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
  60988. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60989. * * 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
  60990. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60991. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60992. * @param name defines the name of the mesh
  60993. * @param options defines the options used to create the mesh
  60994. * @param scene defines the hosting scene
  60995. * @returns the ribbon mesh
  60996. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60997. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60998. */
  60999. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61000. if (scene === void 0) { scene = null; }
  61001. var pathArray = options.pathArray;
  61002. var closeArray = options.closeArray;
  61003. var closePath = options.closePath;
  61004. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61005. var instance = options.instance;
  61006. var updatable = options.updatable;
  61007. if (instance) { // existing ribbon instance update
  61008. // positionFunction : ribbon case
  61009. // only pathArray and sideOrientation parameters are taken into account for positions update
  61010. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61011. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61012. var positionFunction = function (positions) {
  61013. var minlg = pathArray[0].length;
  61014. var i = 0;
  61015. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61016. for (var si = 1; si <= ns; si++) {
  61017. for (var p = 0; p < pathArray.length; p++) {
  61018. var path = pathArray[p];
  61019. var l = path.length;
  61020. minlg = (minlg < l) ? minlg : l;
  61021. var j = 0;
  61022. while (j < minlg) {
  61023. positions[i] = path[j].x;
  61024. positions[i + 1] = path[j].y;
  61025. positions[i + 2] = path[j].z;
  61026. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61027. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61028. }
  61029. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61030. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61031. }
  61032. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61033. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61034. }
  61035. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61036. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61037. }
  61038. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61039. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61040. }
  61041. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61042. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61043. }
  61044. j++;
  61045. i += 3;
  61046. }
  61047. if (instance._closePath) {
  61048. positions[i] = path[0].x;
  61049. positions[i + 1] = path[0].y;
  61050. positions[i + 2] = path[0].z;
  61051. i += 3;
  61052. }
  61053. }
  61054. }
  61055. };
  61056. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61057. positionFunction(positions);
  61058. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61059. instance._boundingInfo.update(instance._worldMatrix);
  61060. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61061. if (options.colors) {
  61062. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61063. for (var c = 0; c < options.colors.length; c++) {
  61064. colors[c * 4] = options.colors[c].r;
  61065. colors[c * 4 + 1] = options.colors[c].g;
  61066. colors[c * 4 + 2] = options.colors[c].b;
  61067. colors[c * 4 + 3] = options.colors[c].a;
  61068. }
  61069. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61070. }
  61071. if (options.uvs) {
  61072. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61073. for (var i = 0; i < options.uvs.length; i++) {
  61074. uvs[i * 2] = options.uvs[i].x;
  61075. uvs[i * 2 + 1] = options.uvs[i].y;
  61076. }
  61077. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61078. }
  61079. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61080. var indices = instance.getIndices();
  61081. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61082. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61083. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61084. if (instance._closePath) {
  61085. var indexFirst = 0;
  61086. var indexLast = 0;
  61087. for (var p = 0; p < pathArray.length; p++) {
  61088. indexFirst = instance._idx[p] * 3;
  61089. if (p + 1 < pathArray.length) {
  61090. indexLast = (instance._idx[p + 1] - 1) * 3;
  61091. }
  61092. else {
  61093. indexLast = normals.length - 3;
  61094. }
  61095. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61096. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61097. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61098. normals[indexLast] = normals[indexFirst];
  61099. normals[indexLast + 1] = normals[indexFirst + 1];
  61100. normals[indexLast + 2] = normals[indexFirst + 2];
  61101. }
  61102. }
  61103. if (!(instance.areNormalsFrozen)) {
  61104. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61105. }
  61106. }
  61107. return instance;
  61108. }
  61109. else { // new ribbon creation
  61110. var ribbon = new BABYLON.Mesh(name, scene);
  61111. ribbon._originalBuilderSideOrientation = sideOrientation;
  61112. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61113. if (closePath) {
  61114. ribbon._idx = vertexData._idx;
  61115. }
  61116. ribbon._closePath = closePath;
  61117. ribbon._closeArray = closeArray;
  61118. vertexData.applyToMesh(ribbon, updatable);
  61119. return ribbon;
  61120. }
  61121. };
  61122. /**
  61123. * Creates a cylinder or a cone mesh
  61124. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61125. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61126. * * 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.
  61127. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61128. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61129. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61130. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61131. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61132. * * 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).
  61133. * * 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
  61134. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61135. * * 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
  61136. * * 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.
  61137. * * If `enclose` is false, a ring surface is one element.
  61138. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61139. * * 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
  61140. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61141. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61142. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61143. * @param name defines the name of the mesh
  61144. * @param options defines the options used to create the mesh
  61145. * @param scene defines the hosting scene
  61146. * @returns the cylinder mesh
  61147. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61148. */
  61149. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61150. var cylinder = new BABYLON.Mesh(name, scene);
  61151. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61152. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61153. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61154. vertexData.applyToMesh(cylinder, options.updatable);
  61155. return cylinder;
  61156. };
  61157. /**
  61158. * Creates a torus mesh
  61159. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61160. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61161. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61162. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61163. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61164. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61165. * @param name defines the name of the mesh
  61166. * @param options defines the options used to create the mesh
  61167. * @param scene defines the hosting scene
  61168. * @returns the torus mesh
  61169. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61170. */
  61171. MeshBuilder.CreateTorus = function (name, options, scene) {
  61172. var torus = new BABYLON.Mesh(name, scene);
  61173. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61174. torus._originalBuilderSideOrientation = options.sideOrientation;
  61175. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61176. vertexData.applyToMesh(torus, options.updatable);
  61177. return torus;
  61178. };
  61179. /**
  61180. * Creates a torus knot mesh
  61181. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61182. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61183. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61184. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61185. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61186. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61187. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61188. * @param name defines the name of the mesh
  61189. * @param options defines the options used to create the mesh
  61190. * @param scene defines the hosting scene
  61191. * @returns the torus knot mesh
  61192. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61193. */
  61194. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61195. var torusKnot = new BABYLON.Mesh(name, scene);
  61196. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61197. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61198. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61199. vertexData.applyToMesh(torusKnot, options.updatable);
  61200. return torusKnot;
  61201. };
  61202. /**
  61203. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61204. * * 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
  61205. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61206. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61207. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61208. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61209. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61210. * * 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
  61211. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61212. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61213. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61214. * @param name defines the name of the new line system
  61215. * @param options defines the options used to create the line system
  61216. * @param scene defines the hosting scene
  61217. * @returns a new line system mesh
  61218. */
  61219. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61220. var instance = options.instance;
  61221. var lines = options.lines;
  61222. var colors = options.colors;
  61223. if (instance) { // lines update
  61224. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61225. var vertexColor;
  61226. var lineColors;
  61227. if (colors) {
  61228. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61229. }
  61230. var i = 0;
  61231. var c = 0;
  61232. for (var l = 0; l < lines.length; l++) {
  61233. var points = lines[l];
  61234. for (var p = 0; p < points.length; p++) {
  61235. positions[i] = points[p].x;
  61236. positions[i + 1] = points[p].y;
  61237. positions[i + 2] = points[p].z;
  61238. if (colors && vertexColor) {
  61239. lineColors = colors[l];
  61240. vertexColor[c] = lineColors[p].r;
  61241. vertexColor[c + 1] = lineColors[p].g;
  61242. vertexColor[c + 2] = lineColors[p].b;
  61243. vertexColor[c + 3] = lineColors[p].a;
  61244. c += 4;
  61245. }
  61246. i += 3;
  61247. }
  61248. }
  61249. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61250. if (colors && vertexColor) {
  61251. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61252. }
  61253. return instance;
  61254. }
  61255. // line system creation
  61256. var useVertexColor = (colors) ? true : false;
  61257. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61258. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61259. vertexData.applyToMesh(lineSystem, options.updatable);
  61260. return lineSystem;
  61261. };
  61262. /**
  61263. * Creates a line mesh
  61264. * 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
  61265. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61266. * * The parameter `points` is an array successive Vector3
  61267. * * 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
  61268. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61269. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61270. * * When updating an instance, remember that only point positions can change, not the number of points
  61271. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61272. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61273. * @param name defines the name of the new line system
  61274. * @param options defines the options used to create the line system
  61275. * @param scene defines the hosting scene
  61276. * @returns a new line mesh
  61277. */
  61278. MeshBuilder.CreateLines = function (name, options, scene) {
  61279. if (scene === void 0) { scene = null; }
  61280. var colors = (options.colors) ? [options.colors] : null;
  61281. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61282. return lines;
  61283. };
  61284. /**
  61285. * Creates a dashed line mesh
  61286. * * 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
  61287. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61288. * * The parameter `points` is an array successive Vector3
  61289. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61290. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61291. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61292. * * 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
  61293. * * When updating an instance, remember that only point positions can change, not the number of points
  61294. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61295. * @param name defines the name of the mesh
  61296. * @param options defines the options used to create the mesh
  61297. * @param scene defines the hosting scene
  61298. * @returns the dashed line mesh
  61299. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61300. */
  61301. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61302. if (scene === void 0) { scene = null; }
  61303. var points = options.points;
  61304. var instance = options.instance;
  61305. var gapSize = options.gapSize || 1;
  61306. var dashSize = options.dashSize || 3;
  61307. if (instance) { // dashed lines update
  61308. var positionFunction = function (positions) {
  61309. var curvect = BABYLON.Vector3.Zero();
  61310. var nbSeg = positions.length / 6;
  61311. var lg = 0;
  61312. var nb = 0;
  61313. var shft = 0;
  61314. var dashshft = 0;
  61315. var curshft = 0;
  61316. var p = 0;
  61317. var i = 0;
  61318. var j = 0;
  61319. for (i = 0; i < points.length - 1; i++) {
  61320. points[i + 1].subtractToRef(points[i], curvect);
  61321. lg += curvect.length();
  61322. }
  61323. shft = lg / nbSeg;
  61324. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61325. for (i = 0; i < points.length - 1; i++) {
  61326. points[i + 1].subtractToRef(points[i], curvect);
  61327. nb = Math.floor(curvect.length() / shft);
  61328. curvect.normalize();
  61329. j = 0;
  61330. while (j < nb && p < positions.length) {
  61331. curshft = shft * j;
  61332. positions[p] = points[i].x + curshft * curvect.x;
  61333. positions[p + 1] = points[i].y + curshft * curvect.y;
  61334. positions[p + 2] = points[i].z + curshft * curvect.z;
  61335. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61336. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61337. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61338. p += 6;
  61339. j++;
  61340. }
  61341. }
  61342. while (p < positions.length) {
  61343. positions[p] = points[i].x;
  61344. positions[p + 1] = points[i].y;
  61345. positions[p + 2] = points[i].z;
  61346. p += 3;
  61347. }
  61348. };
  61349. instance.updateMeshPositions(positionFunction, false);
  61350. return instance;
  61351. }
  61352. // dashed lines creation
  61353. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61354. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61355. vertexData.applyToMesh(dashedLines, options.updatable);
  61356. dashedLines.dashSize = dashSize;
  61357. dashedLines.gapSize = gapSize;
  61358. return dashedLines;
  61359. };
  61360. /**
  61361. * 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.
  61362. * * 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.
  61363. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61364. * * 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.
  61365. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61366. * * 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
  61367. * * 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
  61368. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61369. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61370. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61371. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61372. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61373. * @param name defines the name of the mesh
  61374. * @param options defines the options used to create the mesh
  61375. * @param scene defines the hosting scene
  61376. * @returns the extruded shape mesh
  61377. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61378. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61379. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61380. */
  61381. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61382. if (scene === void 0) { scene = null; }
  61383. var path = options.path;
  61384. var shape = options.shape;
  61385. var scale = options.scale || 1;
  61386. var rotation = options.rotation || 0;
  61387. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61388. var updatable = options.updatable;
  61389. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61390. var instance = options.instance || null;
  61391. var invertUV = options.invertUV || false;
  61392. 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);
  61393. };
  61394. /**
  61395. * Creates an custom extruded shape mesh.
  61396. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61397. * * 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.
  61398. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61399. * * 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
  61400. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61401. * * 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
  61402. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61403. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61404. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61405. * * 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
  61406. * * 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
  61407. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61408. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61409. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61410. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61411. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61412. * @param name defines the name of the mesh
  61413. * @param options defines the options used to create the mesh
  61414. * @param scene defines the hosting scene
  61415. * @returns the custom extruded shape mesh
  61416. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61417. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61418. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61419. */
  61420. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61421. var path = options.path;
  61422. var shape = options.shape;
  61423. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61424. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61425. var ribbonCloseArray = options.ribbonCloseArray || false;
  61426. var ribbonClosePath = options.ribbonClosePath || false;
  61427. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61428. var updatable = options.updatable;
  61429. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61430. var instance = options.instance;
  61431. var invertUV = options.invertUV || false;
  61432. 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);
  61433. };
  61434. /**
  61435. * Creates lathe mesh.
  61436. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61437. * * 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
  61438. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61439. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61440. * * 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
  61441. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61442. * * 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
  61443. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61444. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61445. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61446. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61447. * @param name defines the name of the mesh
  61448. * @param options defines the options used to create the mesh
  61449. * @param scene defines the hosting scene
  61450. * @returns the lathe mesh
  61451. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61452. */
  61453. MeshBuilder.CreateLathe = function (name, options, scene) {
  61454. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61455. var closed = (options.closed === undefined) ? true : options.closed;
  61456. var shape = options.shape;
  61457. var radius = options.radius || 1;
  61458. var tessellation = options.tessellation || 64;
  61459. var updatable = options.updatable;
  61460. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61461. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61462. var pi2 = Math.PI * 2;
  61463. var paths = new Array();
  61464. var invertUV = options.invertUV || false;
  61465. var i = 0;
  61466. var p = 0;
  61467. var step = pi2 / tessellation * arc;
  61468. var rotated;
  61469. var path = new Array();
  61470. for (i = 0; i <= tessellation; i++) {
  61471. var path = [];
  61472. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61473. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61474. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61475. }
  61476. for (p = 0; p < shape.length; p++) {
  61477. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61478. path.push(rotated);
  61479. }
  61480. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61481. 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));
  61482. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61483. }
  61484. paths.push(path);
  61485. }
  61486. // lathe ribbon
  61487. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61488. return lathe;
  61489. };
  61490. /**
  61491. * Creates a plane mesh
  61492. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61493. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61494. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61495. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61496. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61497. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61498. * @param name defines the name of the mesh
  61499. * @param options defines the options used to create the mesh
  61500. * @param scene defines the hosting scene
  61501. * @returns the plane mesh
  61502. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61503. */
  61504. MeshBuilder.CreatePlane = function (name, options, scene) {
  61505. var plane = new BABYLON.Mesh(name, scene);
  61506. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61507. plane._originalBuilderSideOrientation = options.sideOrientation;
  61508. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61509. vertexData.applyToMesh(plane, options.updatable);
  61510. if (options.sourcePlane) {
  61511. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61512. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61513. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61514. plane.rotate(vectorProduct, product);
  61515. }
  61516. return plane;
  61517. };
  61518. /**
  61519. * Creates a ground mesh
  61520. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61521. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61522. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61523. * @param name defines the name of the mesh
  61524. * @param options defines the options used to create the mesh
  61525. * @param scene defines the hosting scene
  61526. * @returns the ground mesh
  61527. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61528. */
  61529. MeshBuilder.CreateGround = function (name, options, scene) {
  61530. var ground = new BABYLON.GroundMesh(name, scene);
  61531. ground._setReady(false);
  61532. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61533. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61534. ground._width = options.width || 1;
  61535. ground._height = options.height || 1;
  61536. ground._maxX = ground._width / 2;
  61537. ground._maxZ = ground._height / 2;
  61538. ground._minX = -ground._maxX;
  61539. ground._minZ = -ground._maxZ;
  61540. var vertexData = BABYLON.VertexData.CreateGround(options);
  61541. vertexData.applyToMesh(ground, options.updatable);
  61542. ground._setReady(true);
  61543. return ground;
  61544. };
  61545. /**
  61546. * Creates a tiled ground mesh
  61547. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61548. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61549. * * 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
  61550. * * 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
  61551. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61552. * @param name defines the name of the mesh
  61553. * @param options defines the options used to create the mesh
  61554. * @param scene defines the hosting scene
  61555. * @returns the tiled ground mesh
  61556. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61557. */
  61558. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61559. var tiledGround = new BABYLON.Mesh(name, scene);
  61560. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61561. vertexData.applyToMesh(tiledGround, options.updatable);
  61562. return tiledGround;
  61563. };
  61564. /**
  61565. * Creates a ground mesh from a height map
  61566. * * The parameter `url` sets the URL of the height map image resource.
  61567. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61568. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61569. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61570. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61571. * * 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.
  61572. * * 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).
  61573. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61574. * @param name defines the name of the mesh
  61575. * @param url defines the url to the height map
  61576. * @param options defines the options used to create the mesh
  61577. * @param scene defines the hosting scene
  61578. * @returns the ground mesh
  61579. * @see http://doc.babylonjs.com/babylon101/height_map
  61580. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61581. */
  61582. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61583. var width = options.width || 10.0;
  61584. var height = options.height || 10.0;
  61585. var subdivisions = options.subdivisions || 1 | 0;
  61586. var minHeight = options.minHeight || 0.0;
  61587. var maxHeight = options.maxHeight || 1.0;
  61588. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61589. var updatable = options.updatable;
  61590. var onReady = options.onReady;
  61591. var ground = new BABYLON.GroundMesh(name, scene);
  61592. ground._subdivisionsX = subdivisions;
  61593. ground._subdivisionsY = subdivisions;
  61594. ground._width = width;
  61595. ground._height = height;
  61596. ground._maxX = ground._width / 2.0;
  61597. ground._maxZ = ground._height / 2.0;
  61598. ground._minX = -ground._maxX;
  61599. ground._minZ = -ground._maxZ;
  61600. ground._setReady(false);
  61601. var onload = function (img) {
  61602. // Getting height map data
  61603. var canvas = document.createElement("canvas");
  61604. var context = canvas.getContext("2d");
  61605. if (!context) {
  61606. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61607. }
  61608. if (scene.isDisposed) {
  61609. return;
  61610. }
  61611. var bufferWidth = img.width;
  61612. var bufferHeight = img.height;
  61613. canvas.width = bufferWidth;
  61614. canvas.height = bufferHeight;
  61615. context.drawImage(img, 0, 0);
  61616. // Create VertexData from map data
  61617. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61618. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61619. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61620. width: width, height: height,
  61621. subdivisions: subdivisions,
  61622. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61623. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61624. });
  61625. vertexData.applyToMesh(ground, updatable);
  61626. //execute ready callback, if set
  61627. if (onReady) {
  61628. onReady(ground);
  61629. }
  61630. ground._setReady(true);
  61631. };
  61632. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61633. return ground;
  61634. };
  61635. /**
  61636. * Creates a polygon mesh
  61637. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61638. * * 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
  61639. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61640. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61641. * * 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)
  61642. * * Remember you can only change the shape positions, not their number when updating a polygon
  61643. * @param name defines the name of the mesh
  61644. * @param options defines the options used to create the mesh
  61645. * @param scene defines the hosting scene
  61646. * @returns the polygon mesh
  61647. */
  61648. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61649. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61650. var shape = options.shape;
  61651. var holes = options.holes || [];
  61652. var depth = options.depth || 0;
  61653. var contours = [];
  61654. var hole = [];
  61655. for (var i = 0; i < shape.length; i++) {
  61656. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61657. }
  61658. var epsilon = 0.00000001;
  61659. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61660. contours.pop();
  61661. }
  61662. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61663. for (var hNb = 0; hNb < holes.length; hNb++) {
  61664. hole = [];
  61665. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61666. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61667. }
  61668. polygonTriangulation.addHole(hole);
  61669. }
  61670. var polygon = polygonTriangulation.build(options.updatable, depth);
  61671. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61672. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61673. vertexData.applyToMesh(polygon, options.updatable);
  61674. return polygon;
  61675. };
  61676. ;
  61677. /**
  61678. * Creates an extruded polygon mesh, with depth in the Y direction.
  61679. * * 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)
  61680. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61681. * @param name defines the name of the mesh
  61682. * @param options defines the options used to create the mesh
  61683. * @param scene defines the hosting scene
  61684. * @returns the polygon mesh
  61685. */
  61686. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61687. return MeshBuilder.CreatePolygon(name, options, scene);
  61688. };
  61689. ;
  61690. /**
  61691. * Creates a tube mesh.
  61692. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61693. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61694. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61695. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61696. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61697. * * 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)
  61698. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61699. * * 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
  61700. * * 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
  61701. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61702. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61703. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61704. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61705. * @param name defines the name of the mesh
  61706. * @param options defines the options used to create the mesh
  61707. * @param scene defines the hosting scene
  61708. * @returns the tube mesh
  61709. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61710. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61711. */
  61712. MeshBuilder.CreateTube = function (name, options, scene) {
  61713. var path = options.path;
  61714. var instance = options.instance;
  61715. var radius = 1.0;
  61716. if (instance) {
  61717. radius = instance.radius;
  61718. }
  61719. if (options.radius !== undefined) {
  61720. radius = options.radius;
  61721. }
  61722. ;
  61723. var tessellation = options.tessellation || 64 | 0;
  61724. var radiusFunction = options.radiusFunction || null;
  61725. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61726. var invertUV = options.invertUV || false;
  61727. var updatable = options.updatable;
  61728. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61729. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61730. // tube geometry
  61731. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61732. var tangents = path3D.getTangents();
  61733. var normals = path3D.getNormals();
  61734. var distances = path3D.getDistances();
  61735. var pi2 = Math.PI * 2;
  61736. var step = pi2 / tessellation * arc;
  61737. var returnRadius = function () { return radius; };
  61738. var radiusFunctionFinal = radiusFunction || returnRadius;
  61739. var circlePath;
  61740. var rad;
  61741. var normal;
  61742. var rotated;
  61743. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61744. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61745. for (var i = 0; i < path.length; i++) {
  61746. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61747. circlePath = Array(); // current circle array
  61748. normal = normals[i]; // current normal
  61749. for (var t = 0; t < tessellation; t++) {
  61750. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61751. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61752. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61753. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61754. circlePath[t] = rotated;
  61755. }
  61756. circlePaths[index] = circlePath;
  61757. index++;
  61758. }
  61759. // cap
  61760. var capPath = function (nbPoints, pathIndex) {
  61761. var pointCap = Array();
  61762. for (var i = 0; i < nbPoints; i++) {
  61763. pointCap.push(path[pathIndex]);
  61764. }
  61765. return pointCap;
  61766. };
  61767. switch (cap) {
  61768. case BABYLON.Mesh.NO_CAP:
  61769. break;
  61770. case BABYLON.Mesh.CAP_START:
  61771. circlePaths[0] = capPath(tessellation, 0);
  61772. circlePaths[1] = circlePaths[2].slice(0);
  61773. break;
  61774. case BABYLON.Mesh.CAP_END:
  61775. circlePaths[index] = circlePaths[index - 1].slice(0);
  61776. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61777. break;
  61778. case BABYLON.Mesh.CAP_ALL:
  61779. circlePaths[0] = capPath(tessellation, 0);
  61780. circlePaths[1] = circlePaths[2].slice(0);
  61781. circlePaths[index] = circlePaths[index - 1].slice(0);
  61782. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61783. break;
  61784. default:
  61785. break;
  61786. }
  61787. return circlePaths;
  61788. };
  61789. var path3D;
  61790. var pathArray;
  61791. if (instance) { // tube update
  61792. var arc = options.arc || instance.arc;
  61793. path3D = (instance.path3D).update(path);
  61794. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61795. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61796. instance.path3D = path3D;
  61797. instance.pathArray = pathArray;
  61798. instance.arc = arc;
  61799. instance.radius = radius;
  61800. return instance;
  61801. }
  61802. // tube creation
  61803. path3D = new BABYLON.Path3D(path);
  61804. var newPathArray = new Array();
  61805. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61806. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61807. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61808. tube.pathArray = pathArray;
  61809. tube.path3D = path3D;
  61810. tube.tessellation = tessellation;
  61811. tube.cap = cap;
  61812. tube.arc = options.arc;
  61813. tube.radius = radius;
  61814. return tube;
  61815. };
  61816. /**
  61817. * Creates a polyhedron mesh
  61818. * * 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
  61819. * * The parameter `size` (positive float, default 1) sets the polygon size
  61820. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61821. * * 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`
  61822. * * 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
  61823. * * 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)`)
  61824. * * 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
  61825. * * 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
  61826. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61827. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61828. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61829. * @param name defines the name of the mesh
  61830. * @param options defines the options used to create the mesh
  61831. * @param scene defines the hosting scene
  61832. * @returns the polyhedron mesh
  61833. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61834. */
  61835. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61836. var polyhedron = new BABYLON.Mesh(name, scene);
  61837. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61838. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61839. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61840. vertexData.applyToMesh(polyhedron, options.updatable);
  61841. return polyhedron;
  61842. };
  61843. /**
  61844. * Creates a decal mesh.
  61845. * 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
  61846. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61847. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61848. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61849. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61850. * @param name defines the name of the mesh
  61851. * @param sourceMesh defines the mesh where the decal must be applied
  61852. * @param options defines the options used to create the mesh
  61853. * @param scene defines the hosting scene
  61854. * @returns the decal mesh
  61855. * @see http://doc.babylonjs.com/how_to/decals
  61856. */
  61857. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61858. var indices = sourceMesh.getIndices();
  61859. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61860. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61861. var position = options.position || BABYLON.Vector3.Zero();
  61862. var normal = options.normal || BABYLON.Vector3.Up();
  61863. var size = options.size || BABYLON.Vector3.One();
  61864. var angle = options.angle || 0;
  61865. // Getting correct rotation
  61866. if (!normal) {
  61867. var target = new BABYLON.Vector3(0, 0, 1);
  61868. var camera = sourceMesh.getScene().activeCamera;
  61869. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61870. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61871. }
  61872. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61873. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61874. var pitch = Math.atan2(normal.y, len);
  61875. // Matrix
  61876. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61877. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61878. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61879. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61880. var vertexData = new BABYLON.VertexData();
  61881. vertexData.indices = [];
  61882. vertexData.positions = [];
  61883. vertexData.normals = [];
  61884. vertexData.uvs = [];
  61885. var currentVertexDataIndex = 0;
  61886. var extractDecalVector3 = function (indexId) {
  61887. var result = new BABYLON.PositionNormalVertex();
  61888. if (!indices || !positions || !normals) {
  61889. return result;
  61890. }
  61891. var vertexId = indices[indexId];
  61892. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61893. // Send vector to decal local world
  61894. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61895. // Get normal
  61896. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61897. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61898. return result;
  61899. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61900. var clip = function (vertices, axis) {
  61901. if (vertices.length === 0) {
  61902. return vertices;
  61903. }
  61904. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61905. var clipVertices = function (v0, v1) {
  61906. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61907. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61908. };
  61909. var result = new Array();
  61910. for (var index = 0; index < vertices.length; index += 3) {
  61911. var v1Out;
  61912. var v2Out;
  61913. var v3Out;
  61914. var total = 0;
  61915. var nV1 = null;
  61916. var nV2 = null;
  61917. var nV3 = null;
  61918. var nV4 = null;
  61919. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61920. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61921. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61922. v1Out = d1 > 0;
  61923. v2Out = d2 > 0;
  61924. v3Out = d3 > 0;
  61925. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61926. switch (total) {
  61927. case 0:
  61928. result.push(vertices[index]);
  61929. result.push(vertices[index + 1]);
  61930. result.push(vertices[index + 2]);
  61931. break;
  61932. case 1:
  61933. if (v1Out) {
  61934. nV1 = vertices[index + 1];
  61935. nV2 = vertices[index + 2];
  61936. nV3 = clipVertices(vertices[index], nV1);
  61937. nV4 = clipVertices(vertices[index], nV2);
  61938. }
  61939. if (v2Out) {
  61940. nV1 = vertices[index];
  61941. nV2 = vertices[index + 2];
  61942. nV3 = clipVertices(vertices[index + 1], nV1);
  61943. nV4 = clipVertices(vertices[index + 1], nV2);
  61944. result.push(nV3);
  61945. result.push(nV2.clone());
  61946. result.push(nV1.clone());
  61947. result.push(nV2.clone());
  61948. result.push(nV3.clone());
  61949. result.push(nV4);
  61950. break;
  61951. }
  61952. if (v3Out) {
  61953. nV1 = vertices[index];
  61954. nV2 = vertices[index + 1];
  61955. nV3 = clipVertices(vertices[index + 2], nV1);
  61956. nV4 = clipVertices(vertices[index + 2], nV2);
  61957. }
  61958. if (nV1 && nV2 && nV3 && nV4) {
  61959. result.push(nV1.clone());
  61960. result.push(nV2.clone());
  61961. result.push(nV3);
  61962. result.push(nV4);
  61963. result.push(nV3.clone());
  61964. result.push(nV2.clone());
  61965. }
  61966. break;
  61967. case 2:
  61968. if (!v1Out) {
  61969. nV1 = vertices[index].clone();
  61970. nV2 = clipVertices(nV1, vertices[index + 1]);
  61971. nV3 = clipVertices(nV1, vertices[index + 2]);
  61972. result.push(nV1);
  61973. result.push(nV2);
  61974. result.push(nV3);
  61975. }
  61976. if (!v2Out) {
  61977. nV1 = vertices[index + 1].clone();
  61978. nV2 = clipVertices(nV1, vertices[index + 2]);
  61979. nV3 = clipVertices(nV1, vertices[index]);
  61980. result.push(nV1);
  61981. result.push(nV2);
  61982. result.push(nV3);
  61983. }
  61984. if (!v3Out) {
  61985. nV1 = vertices[index + 2].clone();
  61986. nV2 = clipVertices(nV1, vertices[index]);
  61987. nV3 = clipVertices(nV1, vertices[index + 1]);
  61988. result.push(nV1);
  61989. result.push(nV2);
  61990. result.push(nV3);
  61991. }
  61992. break;
  61993. case 3:
  61994. break;
  61995. }
  61996. }
  61997. return result;
  61998. };
  61999. for (var index = 0; index < indices.length; index += 3) {
  62000. var faceVertices = new Array();
  62001. faceVertices.push(extractDecalVector3(index));
  62002. faceVertices.push(extractDecalVector3(index + 1));
  62003. faceVertices.push(extractDecalVector3(index + 2));
  62004. // Clip
  62005. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62006. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62007. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62008. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62009. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62010. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62011. if (faceVertices.length === 0) {
  62012. continue;
  62013. }
  62014. // Add UVs and get back to world
  62015. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62016. var vertex = faceVertices[vIndex];
  62017. //TODO check for Int32Array | Uint32Array | Uint16Array
  62018. vertexData.indices.push(currentVertexDataIndex);
  62019. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62020. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62021. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62022. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62023. currentVertexDataIndex++;
  62024. }
  62025. }
  62026. // Return mesh
  62027. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62028. vertexData.applyToMesh(decal);
  62029. decal.position = position.clone();
  62030. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62031. return decal;
  62032. };
  62033. // Privates
  62034. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62035. // extrusion geometry
  62036. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62037. var tangents = path3D.getTangents();
  62038. var normals = path3D.getNormals();
  62039. var binormals = path3D.getBinormals();
  62040. var distances = path3D.getDistances();
  62041. var angle = 0;
  62042. var returnScale = function () { return scale !== null ? scale : 1; };
  62043. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62044. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62045. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62046. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62047. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62048. for (var i = 0; i < curve.length; i++) {
  62049. var shapePath = new Array();
  62050. var angleStep = rotate(i, distances[i]);
  62051. var scaleRatio = scl(i, distances[i]);
  62052. for (var p = 0; p < shape.length; p++) {
  62053. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62054. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62055. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62056. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62057. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62058. shapePath[p] = rotated;
  62059. }
  62060. shapePaths[index] = shapePath;
  62061. angle += angleStep;
  62062. index++;
  62063. }
  62064. // cap
  62065. var capPath = function (shapePath) {
  62066. var pointCap = Array();
  62067. var barycenter = BABYLON.Vector3.Zero();
  62068. var i;
  62069. for (i = 0; i < shapePath.length; i++) {
  62070. barycenter.addInPlace(shapePath[i]);
  62071. }
  62072. barycenter.scaleInPlace(1.0 / shapePath.length);
  62073. for (i = 0; i < shapePath.length; i++) {
  62074. pointCap.push(barycenter);
  62075. }
  62076. return pointCap;
  62077. };
  62078. switch (cap) {
  62079. case BABYLON.Mesh.NO_CAP:
  62080. break;
  62081. case BABYLON.Mesh.CAP_START:
  62082. shapePaths[0] = capPath(shapePaths[2]);
  62083. shapePaths[1] = shapePaths[2];
  62084. break;
  62085. case BABYLON.Mesh.CAP_END:
  62086. shapePaths[index] = shapePaths[index - 1];
  62087. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62088. break;
  62089. case BABYLON.Mesh.CAP_ALL:
  62090. shapePaths[0] = capPath(shapePaths[2]);
  62091. shapePaths[1] = shapePaths[2];
  62092. shapePaths[index] = shapePaths[index - 1];
  62093. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62094. break;
  62095. default:
  62096. break;
  62097. }
  62098. return shapePaths;
  62099. };
  62100. var path3D;
  62101. var pathArray;
  62102. if (instance) { // instance update
  62103. path3D = (instance.path3D).update(curve);
  62104. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62105. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62106. return instance;
  62107. }
  62108. // extruded shape creation
  62109. path3D = new BABYLON.Path3D(curve);
  62110. var newShapePaths = new Array();
  62111. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62112. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62113. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62114. extrudedGeneric.pathArray = pathArray;
  62115. extrudedGeneric.path3D = path3D;
  62116. extrudedGeneric.cap = cap;
  62117. return extrudedGeneric;
  62118. };
  62119. return MeshBuilder;
  62120. }());
  62121. BABYLON.MeshBuilder = MeshBuilder;
  62122. })(BABYLON || (BABYLON = {}));
  62123. //# sourceMappingURL=babylon.meshBuilder.js.map
  62124. var BABYLON;
  62125. (function (BABYLON) {
  62126. /**
  62127. * Draco compression (https://google.github.io/draco/)
  62128. *
  62129. * This class wraps the Draco module.
  62130. *
  62131. * **Encoder**
  62132. *
  62133. * The encoder is not currently implemented.
  62134. *
  62135. * **Decoder**
  62136. *
  62137. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62138. *
  62139. * To update the configuration, use the following code:
  62140. * ```javascript
  62141. * BABYLON.DracoCompression.Configuration = {
  62142. * decoder: {
  62143. * wasmUrl: "<url to the WebAssembly library>",
  62144. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62145. * fallbackUrl: "<url to the fallback JavaScript library>",
  62146. * }
  62147. * };
  62148. * ```
  62149. *
  62150. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62151. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62152. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62153. *
  62154. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62155. * ```javascript
  62156. * var dracoCompression = new BABYLON.DracoCompression();
  62157. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62158. * [BABYLON.VertexBuffer.PositionKind]: 0
  62159. * });
  62160. * ```
  62161. *
  62162. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62163. */
  62164. var DracoCompression = /** @class */ (function () {
  62165. /**
  62166. * Constructor
  62167. */
  62168. function DracoCompression() {
  62169. }
  62170. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62171. /**
  62172. * Returns true if the decoder is available.
  62173. */
  62174. get: function () {
  62175. if (typeof DracoDecoderModule !== "undefined") {
  62176. return true;
  62177. }
  62178. var decoder = DracoCompression.Configuration.decoder;
  62179. if (decoder) {
  62180. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62181. return true;
  62182. }
  62183. if (decoder.fallbackUrl) {
  62184. return true;
  62185. }
  62186. }
  62187. return false;
  62188. },
  62189. enumerable: true,
  62190. configurable: true
  62191. });
  62192. /**
  62193. * Stop all async operations and release resources.
  62194. */
  62195. DracoCompression.prototype.dispose = function () {
  62196. };
  62197. /**
  62198. * Decode Draco compressed mesh data to vertex data.
  62199. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62200. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62201. * @returns A promise that resolves with the decoded vertex data
  62202. */
  62203. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62204. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62205. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62206. var module = wrappedModule.module;
  62207. var vertexData = new BABYLON.VertexData();
  62208. var buffer = new module.DecoderBuffer();
  62209. buffer.Init(dataView, dataView.byteLength);
  62210. var decoder = new module.Decoder();
  62211. var geometry;
  62212. var status;
  62213. try {
  62214. var type = decoder.GetEncodedGeometryType(buffer);
  62215. switch (type) {
  62216. case module.TRIANGULAR_MESH:
  62217. geometry = new module.Mesh();
  62218. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62219. break;
  62220. case module.POINT_CLOUD:
  62221. geometry = new module.PointCloud();
  62222. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62223. break;
  62224. default:
  62225. throw new Error("Invalid geometry type " + type);
  62226. }
  62227. if (!status.ok() || !geometry.ptr) {
  62228. throw new Error(status.error_msg());
  62229. }
  62230. var numPoints = geometry.num_points();
  62231. if (type === module.TRIANGULAR_MESH) {
  62232. var numFaces = geometry.num_faces();
  62233. var faceIndices = new module.DracoInt32Array();
  62234. try {
  62235. var indices = new Uint32Array(numFaces * 3);
  62236. for (var i = 0; i < numFaces; i++) {
  62237. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62238. var offset = i * 3;
  62239. indices[offset + 0] = faceIndices.GetValue(0);
  62240. indices[offset + 1] = faceIndices.GetValue(1);
  62241. indices[offset + 2] = faceIndices.GetValue(2);
  62242. }
  62243. vertexData.indices = indices;
  62244. }
  62245. finally {
  62246. module.destroy(faceIndices);
  62247. }
  62248. }
  62249. for (var kind in attributes) {
  62250. var uniqueId = attributes[kind];
  62251. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62252. var dracoData = new module.DracoFloat32Array();
  62253. try {
  62254. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62255. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62256. for (var i = 0; i < babylonData.length; i++) {
  62257. babylonData[i] = dracoData.GetValue(i);
  62258. }
  62259. vertexData.set(babylonData, kind);
  62260. }
  62261. finally {
  62262. module.destroy(dracoData);
  62263. }
  62264. }
  62265. }
  62266. finally {
  62267. if (geometry) {
  62268. module.destroy(geometry);
  62269. }
  62270. module.destroy(decoder);
  62271. module.destroy(buffer);
  62272. }
  62273. return vertexData;
  62274. });
  62275. };
  62276. DracoCompression._GetDecoderModule = function () {
  62277. if (!DracoCompression._DecoderModulePromise) {
  62278. var promise = null;
  62279. var config_1 = {};
  62280. if (typeof DracoDecoderModule !== "undefined") {
  62281. promise = Promise.resolve();
  62282. }
  62283. else {
  62284. var decoder = DracoCompression.Configuration.decoder;
  62285. if (decoder) {
  62286. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62287. promise = Promise.all([
  62288. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62289. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62290. config_1.wasmBinary = data;
  62291. })
  62292. ]);
  62293. }
  62294. else if (decoder.fallbackUrl) {
  62295. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62296. }
  62297. }
  62298. }
  62299. if (!promise) {
  62300. throw new Error("Draco decoder module is not available");
  62301. }
  62302. DracoCompression._DecoderModulePromise = promise.then(function () {
  62303. return new Promise(function (resolve) {
  62304. config_1.onModuleLoaded = function (decoderModule) {
  62305. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62306. resolve({ module: decoderModule });
  62307. };
  62308. DracoDecoderModule(config_1);
  62309. });
  62310. });
  62311. }
  62312. return DracoCompression._DecoderModulePromise;
  62313. };
  62314. DracoCompression._LoadScriptAsync = function (url) {
  62315. return new Promise(function (resolve, reject) {
  62316. BABYLON.Tools.LoadScript(url, function () {
  62317. resolve();
  62318. }, function (message) {
  62319. reject(new Error(message));
  62320. });
  62321. });
  62322. };
  62323. DracoCompression._LoadFileAsync = function (url) {
  62324. return new Promise(function (resolve, reject) {
  62325. BABYLON.Tools.LoadFile(url, function (data) {
  62326. resolve(data);
  62327. }, undefined, undefined, true, function (request, exception) {
  62328. reject(exception);
  62329. });
  62330. });
  62331. };
  62332. /**
  62333. * The configuration. Defaults to the following urls:
  62334. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62335. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62336. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62337. */
  62338. DracoCompression.Configuration = {
  62339. decoder: {
  62340. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62341. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62342. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62343. }
  62344. };
  62345. return DracoCompression;
  62346. }());
  62347. BABYLON.DracoCompression = DracoCompression;
  62348. })(BABYLON || (BABYLON = {}));
  62349. //# sourceMappingURL=babylon.dracoCompression.js.map
  62350. var BABYLON;
  62351. (function (BABYLON) {
  62352. var AudioEngine = /** @class */ (function () {
  62353. function AudioEngine() {
  62354. this._audioContext = null;
  62355. this._audioContextInitialized = false;
  62356. this.canUseWebAudio = false;
  62357. this.WarnedWebAudioUnsupported = false;
  62358. this.unlocked = false;
  62359. this.isMP3supported = false;
  62360. this.isOGGsupported = false;
  62361. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62362. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62363. this.canUseWebAudio = true;
  62364. }
  62365. var audioElem = document.createElement('audio');
  62366. try {
  62367. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62368. this.isMP3supported = true;
  62369. }
  62370. }
  62371. catch (e) {
  62372. // protect error during capability check.
  62373. }
  62374. try {
  62375. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62376. this.isOGGsupported = true;
  62377. }
  62378. }
  62379. catch (e) {
  62380. // protect error during capability check.
  62381. }
  62382. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62383. this._unlockiOSaudio();
  62384. }
  62385. else {
  62386. this.unlocked = true;
  62387. }
  62388. }
  62389. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62390. get: function () {
  62391. if (!this._audioContextInitialized) {
  62392. this._initializeAudioContext();
  62393. }
  62394. return this._audioContext;
  62395. },
  62396. enumerable: true,
  62397. configurable: true
  62398. });
  62399. AudioEngine.prototype._unlockiOSaudio = function () {
  62400. var _this = this;
  62401. var unlockaudio = function () {
  62402. if (!_this.audioContext) {
  62403. return;
  62404. }
  62405. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62406. var source = _this.audioContext.createBufferSource();
  62407. source.buffer = buffer;
  62408. source.connect(_this.audioContext.destination);
  62409. source.start(0);
  62410. setTimeout(function () {
  62411. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62412. _this.unlocked = true;
  62413. window.removeEventListener('touchend', unlockaudio, false);
  62414. if (_this.onAudioUnlocked) {
  62415. _this.onAudioUnlocked();
  62416. }
  62417. }
  62418. }, 0);
  62419. };
  62420. window.addEventListener('touchend', unlockaudio, false);
  62421. };
  62422. AudioEngine.prototype._initializeAudioContext = function () {
  62423. try {
  62424. if (this.canUseWebAudio) {
  62425. this._audioContext = new AudioContext();
  62426. // create a global volume gain node
  62427. this.masterGain = this._audioContext.createGain();
  62428. this.masterGain.gain.value = 1;
  62429. this.masterGain.connect(this._audioContext.destination);
  62430. this._audioContextInitialized = true;
  62431. }
  62432. }
  62433. catch (e) {
  62434. this.canUseWebAudio = false;
  62435. BABYLON.Tools.Error("Web Audio: " + e.message);
  62436. }
  62437. };
  62438. AudioEngine.prototype.dispose = function () {
  62439. if (this.canUseWebAudio && this._audioContextInitialized) {
  62440. if (this._connectedAnalyser && this._audioContext) {
  62441. this._connectedAnalyser.stopDebugCanvas();
  62442. this._connectedAnalyser.dispose();
  62443. this.masterGain.disconnect();
  62444. this.masterGain.connect(this._audioContext.destination);
  62445. this._connectedAnalyser = null;
  62446. }
  62447. this.masterGain.gain.value = 1;
  62448. }
  62449. this.WarnedWebAudioUnsupported = false;
  62450. };
  62451. AudioEngine.prototype.getGlobalVolume = function () {
  62452. if (this.canUseWebAudio && this._audioContextInitialized) {
  62453. return this.masterGain.gain.value;
  62454. }
  62455. else {
  62456. return -1;
  62457. }
  62458. };
  62459. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62460. if (this.canUseWebAudio && this._audioContextInitialized) {
  62461. this.masterGain.gain.value = newVolume;
  62462. }
  62463. };
  62464. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62465. if (this._connectedAnalyser) {
  62466. this._connectedAnalyser.stopDebugCanvas();
  62467. }
  62468. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62469. this._connectedAnalyser = analyser;
  62470. this.masterGain.disconnect();
  62471. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62472. }
  62473. };
  62474. return AudioEngine;
  62475. }());
  62476. BABYLON.AudioEngine = AudioEngine;
  62477. })(BABYLON || (BABYLON = {}));
  62478. //# sourceMappingURL=babylon.audioEngine.js.map
  62479. var BABYLON;
  62480. (function (BABYLON) {
  62481. var Sound = /** @class */ (function () {
  62482. /**
  62483. * Create a sound and attach it to a scene
  62484. * @param name Name of your sound
  62485. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62486. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62487. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62488. */
  62489. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62490. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62491. var _this = this;
  62492. this.autoplay = false;
  62493. this.loop = false;
  62494. this.useCustomAttenuation = false;
  62495. this.spatialSound = false;
  62496. this.refDistance = 1;
  62497. this.rolloffFactor = 1;
  62498. this.maxDistance = 100;
  62499. this.distanceModel = "linear";
  62500. this._panningModel = "equalpower";
  62501. this._playbackRate = 1;
  62502. this._streaming = false;
  62503. this._startTime = 0;
  62504. this._startOffset = 0;
  62505. this._position = BABYLON.Vector3.Zero();
  62506. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62507. this._volume = 1;
  62508. this._isReadyToPlay = false;
  62509. this.isPlaying = false;
  62510. this.isPaused = false;
  62511. this._isDirectional = false;
  62512. // Used if you'd like to create a directional sound.
  62513. // If not set, the sound will be omnidirectional
  62514. this._coneInnerAngle = 360;
  62515. this._coneOuterAngle = 360;
  62516. this._coneOuterGain = 0;
  62517. this._isOutputConnected = false;
  62518. this._urlType = "Unknown";
  62519. this.name = name;
  62520. this._scene = scene;
  62521. this._readyToPlayCallback = readyToPlayCallback;
  62522. // Default custom attenuation function is a linear attenuation
  62523. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62524. if (currentDistance < maxDistance) {
  62525. return currentVolume * (1 - currentDistance / maxDistance);
  62526. }
  62527. else {
  62528. return 0;
  62529. }
  62530. };
  62531. if (options) {
  62532. this.autoplay = options.autoplay || false;
  62533. this.loop = options.loop || false;
  62534. // if volume === 0, we need another way to check this option
  62535. if (options.volume !== undefined) {
  62536. this._volume = options.volume;
  62537. }
  62538. this.spatialSound = options.spatialSound || false;
  62539. this.maxDistance = options.maxDistance || 100;
  62540. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62541. this.rolloffFactor = options.rolloffFactor || 1;
  62542. this.refDistance = options.refDistance || 1;
  62543. this.distanceModel = options.distanceModel || "linear";
  62544. this._playbackRate = options.playbackRate || 1;
  62545. this._streaming = options.streaming || false;
  62546. }
  62547. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62548. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62549. this._soundGain.gain.value = this._volume;
  62550. this._inputAudioNode = this._soundGain;
  62551. this._ouputAudioNode = this._soundGain;
  62552. if (this.spatialSound) {
  62553. this._createSpatialParameters();
  62554. }
  62555. this._scene.mainSoundTrack.AddSound(this);
  62556. var validParameter = true;
  62557. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62558. if (urlOrArrayBuffer) {
  62559. try {
  62560. if (typeof (urlOrArrayBuffer) === "string")
  62561. this._urlType = "String";
  62562. if (Array.isArray(urlOrArrayBuffer))
  62563. this._urlType = "Array";
  62564. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62565. this._urlType = "ArrayBuffer";
  62566. var urls = [];
  62567. var codecSupportedFound = false;
  62568. switch (this._urlType) {
  62569. case "ArrayBuffer":
  62570. if (urlOrArrayBuffer.byteLength > 0) {
  62571. codecSupportedFound = true;
  62572. this._soundLoaded(urlOrArrayBuffer);
  62573. }
  62574. break;
  62575. case "String":
  62576. urls.push(urlOrArrayBuffer);
  62577. case "Array":
  62578. if (urls.length === 0)
  62579. urls = urlOrArrayBuffer;
  62580. // If we found a supported format, we load it immediately and stop the loop
  62581. for (var i = 0; i < urls.length; i++) {
  62582. var url = urls[i];
  62583. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62584. codecSupportedFound = true;
  62585. }
  62586. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62587. codecSupportedFound = true;
  62588. }
  62589. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62590. codecSupportedFound = true;
  62591. }
  62592. if (url.indexOf("blob:") !== -1) {
  62593. codecSupportedFound = true;
  62594. }
  62595. if (codecSupportedFound) {
  62596. // Loading sound using XHR2
  62597. if (!this._streaming) {
  62598. this._scene._loadFile(url, function (data) {
  62599. _this._soundLoaded(data);
  62600. }, undefined, true, true, function (exception) {
  62601. if (exception) {
  62602. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62603. }
  62604. BABYLON.Tools.Error("Sound creation aborted.");
  62605. _this._scene.mainSoundTrack.RemoveSound(_this);
  62606. });
  62607. }
  62608. // Streaming sound using HTML5 Audio tag
  62609. else {
  62610. this._htmlAudioElement = new Audio(url);
  62611. this._htmlAudioElement.controls = false;
  62612. this._htmlAudioElement.loop = this.loop;
  62613. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62614. this._htmlAudioElement.preload = "auto";
  62615. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62616. _this._isReadyToPlay = true;
  62617. if (_this.autoplay) {
  62618. _this.play();
  62619. }
  62620. if (_this._readyToPlayCallback) {
  62621. _this._readyToPlayCallback();
  62622. }
  62623. });
  62624. document.body.appendChild(this._htmlAudioElement);
  62625. }
  62626. break;
  62627. }
  62628. }
  62629. break;
  62630. default:
  62631. validParameter = false;
  62632. break;
  62633. }
  62634. if (!validParameter) {
  62635. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62636. }
  62637. else {
  62638. if (!codecSupportedFound) {
  62639. this._isReadyToPlay = true;
  62640. // Simulating a ready to play event to avoid breaking code path
  62641. if (this._readyToPlayCallback) {
  62642. window.setTimeout(function () {
  62643. if (_this._readyToPlayCallback) {
  62644. _this._readyToPlayCallback();
  62645. }
  62646. }, 1000);
  62647. }
  62648. }
  62649. }
  62650. }
  62651. catch (ex) {
  62652. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62653. this._scene.mainSoundTrack.RemoveSound(this);
  62654. }
  62655. }
  62656. }
  62657. else {
  62658. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62659. this._scene.mainSoundTrack.AddSound(this);
  62660. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62661. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62662. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62663. }
  62664. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62665. if (this._readyToPlayCallback) {
  62666. window.setTimeout(function () {
  62667. if (_this._readyToPlayCallback) {
  62668. _this._readyToPlayCallback();
  62669. }
  62670. }, 1000);
  62671. }
  62672. }
  62673. }
  62674. Sound.prototype.dispose = function () {
  62675. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62676. if (this.isPlaying) {
  62677. this.stop();
  62678. }
  62679. this._isReadyToPlay = false;
  62680. if (this.soundTrackId === -1) {
  62681. this._scene.mainSoundTrack.RemoveSound(this);
  62682. }
  62683. else {
  62684. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62685. }
  62686. if (this._soundGain) {
  62687. this._soundGain.disconnect();
  62688. this._soundGain = null;
  62689. }
  62690. if (this._soundPanner) {
  62691. this._soundPanner.disconnect();
  62692. this._soundPanner = null;
  62693. }
  62694. if (this._soundSource) {
  62695. this._soundSource.disconnect();
  62696. this._soundSource = null;
  62697. }
  62698. this._audioBuffer = null;
  62699. if (this._htmlAudioElement) {
  62700. this._htmlAudioElement.pause();
  62701. this._htmlAudioElement.src = "";
  62702. document.body.removeChild(this._htmlAudioElement);
  62703. }
  62704. if (this._connectedMesh && this._registerFunc) {
  62705. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62706. this._connectedMesh = null;
  62707. }
  62708. }
  62709. };
  62710. Sound.prototype.isReady = function () {
  62711. return this._isReadyToPlay;
  62712. };
  62713. Sound.prototype._soundLoaded = function (audioData) {
  62714. var _this = this;
  62715. if (!BABYLON.Engine.audioEngine.audioContext) {
  62716. return;
  62717. }
  62718. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62719. _this._audioBuffer = buffer;
  62720. _this._isReadyToPlay = true;
  62721. if (_this.autoplay) {
  62722. _this.play();
  62723. }
  62724. if (_this._readyToPlayCallback) {
  62725. _this._readyToPlayCallback();
  62726. }
  62727. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62728. };
  62729. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62730. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62731. this._audioBuffer = audioBuffer;
  62732. this._isReadyToPlay = true;
  62733. }
  62734. };
  62735. Sound.prototype.updateOptions = function (options) {
  62736. if (options) {
  62737. this.loop = options.loop || this.loop;
  62738. this.maxDistance = options.maxDistance || this.maxDistance;
  62739. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62740. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62741. this.refDistance = options.refDistance || this.refDistance;
  62742. this.distanceModel = options.distanceModel || this.distanceModel;
  62743. this._playbackRate = options.playbackRate || this._playbackRate;
  62744. this._updateSpatialParameters();
  62745. if (this.isPlaying) {
  62746. if (this._streaming) {
  62747. this._htmlAudioElement.playbackRate = this._playbackRate;
  62748. }
  62749. else {
  62750. if (this._soundSource) {
  62751. this._soundSource.playbackRate.value = this._playbackRate;
  62752. }
  62753. }
  62754. }
  62755. }
  62756. };
  62757. Sound.prototype._createSpatialParameters = function () {
  62758. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62759. if (this._scene.headphone) {
  62760. this._panningModel = "HRTF";
  62761. }
  62762. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62763. this._updateSpatialParameters();
  62764. this._soundPanner.connect(this._ouputAudioNode);
  62765. this._inputAudioNode = this._soundPanner;
  62766. }
  62767. };
  62768. Sound.prototype._updateSpatialParameters = function () {
  62769. if (this.spatialSound && this._soundPanner) {
  62770. if (this.useCustomAttenuation) {
  62771. // Tricks to disable in a way embedded Web Audio attenuation
  62772. this._soundPanner.distanceModel = "linear";
  62773. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62774. this._soundPanner.refDistance = 1;
  62775. this._soundPanner.rolloffFactor = 1;
  62776. this._soundPanner.panningModel = this._panningModel;
  62777. }
  62778. else {
  62779. this._soundPanner.distanceModel = this.distanceModel;
  62780. this._soundPanner.maxDistance = this.maxDistance;
  62781. this._soundPanner.refDistance = this.refDistance;
  62782. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62783. this._soundPanner.panningModel = this._panningModel;
  62784. }
  62785. }
  62786. };
  62787. Sound.prototype.switchPanningModelToHRTF = function () {
  62788. this._panningModel = "HRTF";
  62789. this._switchPanningModel();
  62790. };
  62791. Sound.prototype.switchPanningModelToEqualPower = function () {
  62792. this._panningModel = "equalpower";
  62793. this._switchPanningModel();
  62794. };
  62795. Sound.prototype._switchPanningModel = function () {
  62796. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62797. this._soundPanner.panningModel = this._panningModel;
  62798. }
  62799. };
  62800. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62801. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62802. if (this._isOutputConnected) {
  62803. this._ouputAudioNode.disconnect();
  62804. }
  62805. this._ouputAudioNode.connect(soundTrackAudioNode);
  62806. this._isOutputConnected = true;
  62807. }
  62808. };
  62809. /**
  62810. * Transform this sound into a directional source
  62811. * @param coneInnerAngle Size of the inner cone in degree
  62812. * @param coneOuterAngle Size of the outer cone in degree
  62813. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62814. */
  62815. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62816. if (coneOuterAngle < coneInnerAngle) {
  62817. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62818. return;
  62819. }
  62820. this._coneInnerAngle = coneInnerAngle;
  62821. this._coneOuterAngle = coneOuterAngle;
  62822. this._coneOuterGain = coneOuterGain;
  62823. this._isDirectional = true;
  62824. if (this.isPlaying && this.loop) {
  62825. this.stop();
  62826. this.play();
  62827. }
  62828. };
  62829. Sound.prototype.setPosition = function (newPosition) {
  62830. this._position = newPosition;
  62831. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62832. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62833. }
  62834. };
  62835. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62836. this._localDirection = newLocalDirection;
  62837. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62838. this._updateDirection();
  62839. }
  62840. };
  62841. Sound.prototype._updateDirection = function () {
  62842. if (!this._connectedMesh || !this._soundPanner) {
  62843. return;
  62844. }
  62845. var mat = this._connectedMesh.getWorldMatrix();
  62846. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62847. direction.normalize();
  62848. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62849. };
  62850. Sound.prototype.updateDistanceFromListener = function () {
  62851. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62852. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62853. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62854. }
  62855. };
  62856. Sound.prototype.setAttenuationFunction = function (callback) {
  62857. this._customAttenuationFunction = callback;
  62858. };
  62859. /**
  62860. * Play the sound
  62861. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62862. * @param offset (optional) Start the sound setting it at a specific time
  62863. */
  62864. Sound.prototype.play = function (time, offset) {
  62865. var _this = this;
  62866. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62867. try {
  62868. if (this._startOffset < 0) {
  62869. time = -this._startOffset;
  62870. this._startOffset = 0;
  62871. }
  62872. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62873. if (!this._soundSource || !this._streamingSource) {
  62874. if (this.spatialSound && this._soundPanner) {
  62875. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62876. if (this._isDirectional) {
  62877. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62878. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62879. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62880. if (this._connectedMesh) {
  62881. this._updateDirection();
  62882. }
  62883. else {
  62884. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62885. }
  62886. }
  62887. }
  62888. }
  62889. if (this._streaming) {
  62890. if (!this._streamingSource) {
  62891. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62892. this._htmlAudioElement.onended = function () { _this._onended(); };
  62893. this._htmlAudioElement.playbackRate = this._playbackRate;
  62894. }
  62895. this._streamingSource.disconnect();
  62896. this._streamingSource.connect(this._inputAudioNode);
  62897. this._htmlAudioElement.play();
  62898. }
  62899. else {
  62900. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62901. this._soundSource.buffer = this._audioBuffer;
  62902. this._soundSource.connect(this._inputAudioNode);
  62903. this._soundSource.loop = this.loop;
  62904. this._soundSource.playbackRate.value = this._playbackRate;
  62905. this._soundSource.onended = function () { _this._onended(); };
  62906. if (this._soundSource.buffer) {
  62907. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62908. }
  62909. }
  62910. this._startTime = startTime;
  62911. this.isPlaying = true;
  62912. this.isPaused = false;
  62913. }
  62914. catch (ex) {
  62915. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62916. }
  62917. }
  62918. };
  62919. Sound.prototype._onended = function () {
  62920. this.isPlaying = false;
  62921. if (this.onended) {
  62922. this.onended();
  62923. }
  62924. };
  62925. /**
  62926. * Stop the sound
  62927. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62928. */
  62929. Sound.prototype.stop = function (time) {
  62930. if (this.isPlaying) {
  62931. if (this._streaming) {
  62932. this._htmlAudioElement.pause();
  62933. // Test needed for Firefox or it will generate an Invalid State Error
  62934. if (this._htmlAudioElement.currentTime > 0) {
  62935. this._htmlAudioElement.currentTime = 0;
  62936. }
  62937. }
  62938. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62939. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62940. this._soundSource.stop(stopTime);
  62941. this._soundSource.onended = function () { };
  62942. if (!this.isPaused) {
  62943. this._startOffset = 0;
  62944. }
  62945. }
  62946. this.isPlaying = false;
  62947. }
  62948. };
  62949. Sound.prototype.pause = function () {
  62950. if (this.isPlaying) {
  62951. this.isPaused = true;
  62952. if (this._streaming) {
  62953. this._htmlAudioElement.pause();
  62954. }
  62955. else if (BABYLON.Engine.audioEngine.audioContext) {
  62956. this.stop(0);
  62957. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62958. }
  62959. }
  62960. };
  62961. Sound.prototype.setVolume = function (newVolume, time) {
  62962. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62963. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62964. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62965. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62966. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62967. }
  62968. else {
  62969. this._soundGain.gain.value = newVolume;
  62970. }
  62971. }
  62972. this._volume = newVolume;
  62973. };
  62974. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62975. this._playbackRate = newPlaybackRate;
  62976. if (this.isPlaying) {
  62977. if (this._streaming) {
  62978. this._htmlAudioElement.playbackRate = this._playbackRate;
  62979. }
  62980. else if (this._soundSource) {
  62981. this._soundSource.playbackRate.value = this._playbackRate;
  62982. }
  62983. }
  62984. };
  62985. Sound.prototype.getVolume = function () {
  62986. return this._volume;
  62987. };
  62988. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62989. var _this = this;
  62990. if (this._connectedMesh && this._registerFunc) {
  62991. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62992. this._registerFunc = null;
  62993. }
  62994. this._connectedMesh = meshToConnectTo;
  62995. if (!this.spatialSound) {
  62996. this.spatialSound = true;
  62997. this._createSpatialParameters();
  62998. if (this.isPlaying && this.loop) {
  62999. this.stop();
  63000. this.play();
  63001. }
  63002. }
  63003. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63004. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63005. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63006. };
  63007. Sound.prototype.detachFromMesh = function () {
  63008. if (this._connectedMesh && this._registerFunc) {
  63009. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63010. this._registerFunc = null;
  63011. this._connectedMesh = null;
  63012. }
  63013. };
  63014. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63015. if (!node.getBoundingInfo) {
  63016. return;
  63017. }
  63018. var mesh = node;
  63019. var boundingInfo = mesh.getBoundingInfo();
  63020. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63021. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63022. this._updateDirection();
  63023. }
  63024. };
  63025. Sound.prototype.clone = function () {
  63026. var _this = this;
  63027. if (!this._streaming) {
  63028. var setBufferAndRun = function () {
  63029. if (_this._isReadyToPlay) {
  63030. clonedSound._audioBuffer = _this.getAudioBuffer();
  63031. clonedSound._isReadyToPlay = true;
  63032. if (clonedSound.autoplay) {
  63033. clonedSound.play();
  63034. }
  63035. }
  63036. else {
  63037. window.setTimeout(setBufferAndRun, 300);
  63038. }
  63039. };
  63040. var currentOptions = {
  63041. autoplay: this.autoplay, loop: this.loop,
  63042. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63043. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63044. refDistance: this.refDistance, distanceModel: this.distanceModel
  63045. };
  63046. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63047. if (this.useCustomAttenuation) {
  63048. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63049. }
  63050. clonedSound.setPosition(this._position);
  63051. clonedSound.setPlaybackRate(this._playbackRate);
  63052. setBufferAndRun();
  63053. return clonedSound;
  63054. }
  63055. // Can't clone a streaming sound
  63056. else {
  63057. return null;
  63058. }
  63059. };
  63060. Sound.prototype.getAudioBuffer = function () {
  63061. return this._audioBuffer;
  63062. };
  63063. Sound.prototype.serialize = function () {
  63064. var serializationObject = {
  63065. name: this.name,
  63066. url: this.name,
  63067. autoplay: this.autoplay,
  63068. loop: this.loop,
  63069. volume: this._volume,
  63070. spatialSound: this.spatialSound,
  63071. maxDistance: this.maxDistance,
  63072. rolloffFactor: this.rolloffFactor,
  63073. refDistance: this.refDistance,
  63074. distanceModel: this.distanceModel,
  63075. playbackRate: this._playbackRate,
  63076. panningModel: this._panningModel,
  63077. soundTrackId: this.soundTrackId
  63078. };
  63079. if (this.spatialSound) {
  63080. if (this._connectedMesh)
  63081. serializationObject.connectedMeshId = this._connectedMesh.id;
  63082. serializationObject.position = this._position.asArray();
  63083. serializationObject.refDistance = this.refDistance;
  63084. serializationObject.distanceModel = this.distanceModel;
  63085. serializationObject.isDirectional = this._isDirectional;
  63086. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63087. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63088. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63089. serializationObject.coneOuterGain = this._coneOuterGain;
  63090. }
  63091. return serializationObject;
  63092. };
  63093. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63094. var soundName = parsedSound.name;
  63095. var soundUrl;
  63096. if (parsedSound.url) {
  63097. soundUrl = rootUrl + parsedSound.url;
  63098. }
  63099. else {
  63100. soundUrl = rootUrl + soundName;
  63101. }
  63102. var options = {
  63103. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63104. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63105. rolloffFactor: parsedSound.rolloffFactor,
  63106. refDistance: parsedSound.refDistance,
  63107. distanceModel: parsedSound.distanceModel,
  63108. playbackRate: parsedSound.playbackRate
  63109. };
  63110. var newSound;
  63111. if (!sourceSound) {
  63112. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63113. scene._addPendingData(newSound);
  63114. }
  63115. else {
  63116. var setBufferAndRun = function () {
  63117. if (sourceSound._isReadyToPlay) {
  63118. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63119. newSound._isReadyToPlay = true;
  63120. if (newSound.autoplay) {
  63121. newSound.play();
  63122. }
  63123. }
  63124. else {
  63125. window.setTimeout(setBufferAndRun, 300);
  63126. }
  63127. };
  63128. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63129. setBufferAndRun();
  63130. }
  63131. if (parsedSound.position) {
  63132. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63133. newSound.setPosition(soundPosition);
  63134. }
  63135. if (parsedSound.isDirectional) {
  63136. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63137. if (parsedSound.localDirectionToMesh) {
  63138. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63139. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63140. }
  63141. }
  63142. if (parsedSound.connectedMeshId) {
  63143. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63144. if (connectedMesh) {
  63145. newSound.attachToMesh(connectedMesh);
  63146. }
  63147. }
  63148. return newSound;
  63149. };
  63150. return Sound;
  63151. }());
  63152. BABYLON.Sound = Sound;
  63153. })(BABYLON || (BABYLON = {}));
  63154. //# sourceMappingURL=babylon.sound.js.map
  63155. var BABYLON;
  63156. (function (BABYLON) {
  63157. var SoundTrack = /** @class */ (function () {
  63158. function SoundTrack(scene, options) {
  63159. this.id = -1;
  63160. this._isMainTrack = false;
  63161. this._isInitialized = false;
  63162. this._scene = scene;
  63163. this.soundCollection = new Array();
  63164. this._options = options;
  63165. if (!this._isMainTrack) {
  63166. this._scene.soundTracks.push(this);
  63167. this.id = this._scene.soundTracks.length - 1;
  63168. }
  63169. }
  63170. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63171. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63172. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63173. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63174. if (this._options) {
  63175. if (this._options.volume) {
  63176. this._outputAudioNode.gain.value = this._options.volume;
  63177. }
  63178. if (this._options.mainTrack) {
  63179. this._isMainTrack = this._options.mainTrack;
  63180. }
  63181. }
  63182. this._isInitialized = true;
  63183. }
  63184. };
  63185. SoundTrack.prototype.dispose = function () {
  63186. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63187. if (this._connectedAnalyser) {
  63188. this._connectedAnalyser.stopDebugCanvas();
  63189. }
  63190. while (this.soundCollection.length) {
  63191. this.soundCollection[0].dispose();
  63192. }
  63193. if (this._outputAudioNode) {
  63194. this._outputAudioNode.disconnect();
  63195. }
  63196. this._outputAudioNode = null;
  63197. }
  63198. };
  63199. SoundTrack.prototype.AddSound = function (sound) {
  63200. if (!this._isInitialized) {
  63201. this._initializeSoundTrackAudioGraph();
  63202. }
  63203. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63204. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63205. }
  63206. if (sound.soundTrackId) {
  63207. if (sound.soundTrackId === -1) {
  63208. this._scene.mainSoundTrack.RemoveSound(sound);
  63209. }
  63210. else {
  63211. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63212. }
  63213. }
  63214. this.soundCollection.push(sound);
  63215. sound.soundTrackId = this.id;
  63216. };
  63217. SoundTrack.prototype.RemoveSound = function (sound) {
  63218. var index = this.soundCollection.indexOf(sound);
  63219. if (index !== -1) {
  63220. this.soundCollection.splice(index, 1);
  63221. }
  63222. };
  63223. SoundTrack.prototype.setVolume = function (newVolume) {
  63224. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63225. this._outputAudioNode.gain.value = newVolume;
  63226. }
  63227. };
  63228. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63229. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63230. for (var i = 0; i < this.soundCollection.length; i++) {
  63231. this.soundCollection[i].switchPanningModelToHRTF();
  63232. }
  63233. }
  63234. };
  63235. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63236. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63237. for (var i = 0; i < this.soundCollection.length; i++) {
  63238. this.soundCollection[i].switchPanningModelToEqualPower();
  63239. }
  63240. }
  63241. };
  63242. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63243. if (this._connectedAnalyser) {
  63244. this._connectedAnalyser.stopDebugCanvas();
  63245. }
  63246. this._connectedAnalyser = analyser;
  63247. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63248. this._outputAudioNode.disconnect();
  63249. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63250. }
  63251. };
  63252. return SoundTrack;
  63253. }());
  63254. BABYLON.SoundTrack = SoundTrack;
  63255. })(BABYLON || (BABYLON = {}));
  63256. //# sourceMappingURL=babylon.soundtrack.js.map
  63257. var BABYLON;
  63258. (function (BABYLON) {
  63259. /**
  63260. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63261. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63262. */
  63263. var Analyser = /** @class */ (function () {
  63264. /**
  63265. * Creates a new analyser
  63266. * @param scene defines hosting scene
  63267. */
  63268. function Analyser(scene) {
  63269. /**
  63270. * Gets or sets the smoothing
  63271. * @ignorenaming
  63272. */
  63273. this.SMOOTHING = 0.75;
  63274. /**
  63275. * Gets or sets the FFT table size
  63276. * @ignorenaming
  63277. */
  63278. this.FFT_SIZE = 512;
  63279. /**
  63280. * Gets or sets the bar graph amplitude
  63281. * @ignorenaming
  63282. */
  63283. this.BARGRAPHAMPLITUDE = 256;
  63284. /**
  63285. * Gets or sets the position of the debug canvas
  63286. * @ignorenaming
  63287. */
  63288. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63289. /**
  63290. * Gets or sets the debug canvas size
  63291. * @ignorenaming
  63292. */
  63293. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63294. this._scene = scene;
  63295. this._audioEngine = BABYLON.Engine.audioEngine;
  63296. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63297. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63298. this._webAudioAnalyser.minDecibels = -140;
  63299. this._webAudioAnalyser.maxDecibels = 0;
  63300. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63301. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63302. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63303. }
  63304. }
  63305. /**
  63306. * Get the number of data values you will have to play with for the visualization
  63307. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63308. * @returns a number
  63309. */
  63310. Analyser.prototype.getFrequencyBinCount = function () {
  63311. if (this._audioEngine.canUseWebAudio) {
  63312. return this._webAudioAnalyser.frequencyBinCount;
  63313. }
  63314. else {
  63315. return 0;
  63316. }
  63317. };
  63318. /**
  63319. * Gets the current frequency data as a byte array
  63320. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63321. * @returns a Uint8Array
  63322. */
  63323. Analyser.prototype.getByteFrequencyData = function () {
  63324. if (this._audioEngine.canUseWebAudio) {
  63325. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63326. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63327. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63328. }
  63329. return this._byteFreqs;
  63330. };
  63331. /**
  63332. * Gets the current waveform as a byte array
  63333. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63334. * @returns a Uint8Array
  63335. */
  63336. Analyser.prototype.getByteTimeDomainData = function () {
  63337. if (this._audioEngine.canUseWebAudio) {
  63338. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63339. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63340. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63341. }
  63342. return this._byteTime;
  63343. };
  63344. /**
  63345. * Gets the current frequency data as a float array
  63346. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63347. * @returns a Float32Array
  63348. */
  63349. Analyser.prototype.getFloatFrequencyData = function () {
  63350. if (this._audioEngine.canUseWebAudio) {
  63351. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63352. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63353. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63354. }
  63355. return this._floatFreqs;
  63356. };
  63357. /**
  63358. * Renders the debug canvas
  63359. */
  63360. Analyser.prototype.drawDebugCanvas = function () {
  63361. var _this = this;
  63362. if (this._audioEngine.canUseWebAudio) {
  63363. if (!this._debugCanvas) {
  63364. this._debugCanvas = document.createElement("canvas");
  63365. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63366. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63367. this._debugCanvas.style.position = "absolute";
  63368. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63369. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63370. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63371. document.body.appendChild(this._debugCanvas);
  63372. this._registerFunc = function () {
  63373. _this.drawDebugCanvas();
  63374. };
  63375. this._scene.registerBeforeRender(this._registerFunc);
  63376. }
  63377. if (this._registerFunc && this._debugCanvasContext) {
  63378. var workingArray = this.getByteFrequencyData();
  63379. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63380. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63381. // Draw the frequency domain chart.
  63382. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63383. var value = workingArray[i];
  63384. var percent = value / this.BARGRAPHAMPLITUDE;
  63385. var height = this.DEBUGCANVASSIZE.height * percent;
  63386. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63387. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63388. var hue = i / this.getFrequencyBinCount() * 360;
  63389. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63390. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63391. }
  63392. }
  63393. }
  63394. };
  63395. /**
  63396. * Stops rendering the debug canvas and removes it
  63397. */
  63398. Analyser.prototype.stopDebugCanvas = function () {
  63399. if (this._debugCanvas) {
  63400. if (this._registerFunc) {
  63401. this._scene.unregisterBeforeRender(this._registerFunc);
  63402. this._registerFunc = null;
  63403. }
  63404. document.body.removeChild(this._debugCanvas);
  63405. this._debugCanvas = null;
  63406. this._debugCanvasContext = null;
  63407. }
  63408. };
  63409. /**
  63410. * Connects two audio nodes
  63411. * @param inputAudioNode defines first node to connect
  63412. * @param outputAudioNode defines second node to connect
  63413. */
  63414. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63415. if (this._audioEngine.canUseWebAudio) {
  63416. inputAudioNode.connect(this._webAudioAnalyser);
  63417. this._webAudioAnalyser.connect(outputAudioNode);
  63418. }
  63419. };
  63420. /**
  63421. * Releases all associated resources
  63422. */
  63423. Analyser.prototype.dispose = function () {
  63424. if (this._audioEngine.canUseWebAudio) {
  63425. this._webAudioAnalyser.disconnect();
  63426. }
  63427. };
  63428. return Analyser;
  63429. }());
  63430. BABYLON.Analyser = Analyser;
  63431. })(BABYLON || (BABYLON = {}));
  63432. //# sourceMappingURL=babylon.analyser.js.map
  63433. var BABYLON;
  63434. (function (BABYLON) {
  63435. var CubeTexture = /** @class */ (function (_super) {
  63436. __extends(CubeTexture, _super);
  63437. /**
  63438. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63439. * as prefiltered data.
  63440. * @param rootUrl defines the url of the texture or the root name of the six images
  63441. * @param scene defines the scene the texture is attached to
  63442. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63443. * @param noMipmap defines if mipmaps should be created or not
  63444. * @param files defines the six files to load for the different faces
  63445. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63446. * @param onError defines a callback triggered in case of error during load
  63447. * @param format defines the internal format to use for the texture once loaded
  63448. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63449. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63450. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63451. * @return the cube texture
  63452. */
  63453. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63454. if (extensions === void 0) { extensions = null; }
  63455. if (noMipmap === void 0) { noMipmap = false; }
  63456. if (files === void 0) { files = null; }
  63457. if (onLoad === void 0) { onLoad = null; }
  63458. if (onError === void 0) { onError = null; }
  63459. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63460. if (prefiltered === void 0) { prefiltered = false; }
  63461. if (forcedExtension === void 0) { forcedExtension = null; }
  63462. if (createPolynomials === void 0) { createPolynomials = false; }
  63463. var _this = _super.call(this, scene) || this;
  63464. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63465. /**
  63466. * Gets or sets the center of the bounding box associated with the cube texture
  63467. * It must define where the camera used to render the texture was set
  63468. */
  63469. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63470. _this._rotationY = 0;
  63471. _this.name = rootUrl;
  63472. _this.url = rootUrl;
  63473. _this._noMipmap = noMipmap;
  63474. _this.hasAlpha = false;
  63475. _this._format = format;
  63476. _this._prefiltered = prefiltered;
  63477. _this.isCube = true;
  63478. _this._textureMatrix = BABYLON.Matrix.Identity();
  63479. _this._createPolynomials = createPolynomials;
  63480. if (prefiltered) {
  63481. _this.gammaSpace = false;
  63482. }
  63483. if (!rootUrl && !files) {
  63484. return _this;
  63485. }
  63486. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63487. var lastDot = rootUrl.lastIndexOf(".");
  63488. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63489. var isDDS = (extension === ".dds");
  63490. if (!files) {
  63491. if (!isDDS && !extensions) {
  63492. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63493. }
  63494. files = [];
  63495. if (extensions) {
  63496. for (var index = 0; index < extensions.length; index++) {
  63497. files.push(rootUrl + extensions[index]);
  63498. }
  63499. }
  63500. }
  63501. _this._files = files;
  63502. if (!_this._texture) {
  63503. if (!scene.useDelayedTextureLoading) {
  63504. if (prefiltered) {
  63505. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63506. }
  63507. else {
  63508. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63509. }
  63510. }
  63511. else {
  63512. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63513. }
  63514. }
  63515. else if (onLoad) {
  63516. if (_this._texture.isReady) {
  63517. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63518. }
  63519. else {
  63520. _this._texture.onLoadedObservable.add(onLoad);
  63521. }
  63522. }
  63523. return _this;
  63524. }
  63525. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63526. get: function () {
  63527. return this._boundingBoxSize;
  63528. },
  63529. /**
  63530. * Gets or sets the size of the bounding box associated with the cube texture
  63531. * When defined, the cubemap will switch to local mode
  63532. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63533. * @example https://www.babylonjs-playground.com/#RNASML
  63534. */
  63535. set: function (value) {
  63536. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63537. return;
  63538. }
  63539. this._boundingBoxSize = value;
  63540. var scene = this.getScene();
  63541. if (scene) {
  63542. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63543. }
  63544. },
  63545. enumerable: true,
  63546. configurable: true
  63547. });
  63548. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63549. /**
  63550. * Gets texture matrix rotation angle around Y axis radians.
  63551. */
  63552. get: function () {
  63553. return this._rotationY;
  63554. },
  63555. /**
  63556. * Sets texture matrix rotation angle around Y axis in radians.
  63557. */
  63558. set: function (value) {
  63559. this._rotationY = value;
  63560. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63561. },
  63562. enumerable: true,
  63563. configurable: true
  63564. });
  63565. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63566. var rootUrlKey = "";
  63567. files.forEach(function (url) { return rootUrlKey += url; });
  63568. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63569. };
  63570. /**
  63571. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63572. * @param url defines the url of the prefiltered texture
  63573. * @param scene defines the scene the texture is attached to
  63574. * @param forcedExtension defines the extension of the file if different from the url
  63575. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63576. * @return the prefiltered texture
  63577. */
  63578. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63579. if (forcedExtension === void 0) { forcedExtension = null; }
  63580. if (createPolynomials === void 0) { createPolynomials = true; }
  63581. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63582. };
  63583. // Methods
  63584. CubeTexture.prototype.delayLoad = function () {
  63585. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63586. return;
  63587. }
  63588. var scene = this.getScene();
  63589. if (!scene) {
  63590. return;
  63591. }
  63592. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63593. this._texture = this._getFromCache(this.url, this._noMipmap);
  63594. if (!this._texture) {
  63595. if (this._prefiltered) {
  63596. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63597. }
  63598. else {
  63599. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63600. }
  63601. }
  63602. };
  63603. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63604. return this._textureMatrix;
  63605. };
  63606. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63607. this._textureMatrix = value;
  63608. };
  63609. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63610. var texture = BABYLON.SerializationHelper.Parse(function () {
  63611. var prefiltered = false;
  63612. if (parsedTexture.prefiltered) {
  63613. prefiltered = parsedTexture.prefiltered;
  63614. }
  63615. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63616. }, parsedTexture, scene);
  63617. // Local Cubemaps
  63618. if (parsedTexture.boundingBoxPosition) {
  63619. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63620. }
  63621. if (parsedTexture.boundingBoxSize) {
  63622. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63623. }
  63624. // Animations
  63625. if (parsedTexture.animations) {
  63626. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63627. var parsedAnimation = parsedTexture.animations[animationIndex];
  63628. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63629. }
  63630. }
  63631. return texture;
  63632. };
  63633. CubeTexture.prototype.clone = function () {
  63634. var _this = this;
  63635. return BABYLON.SerializationHelper.Clone(function () {
  63636. var scene = _this.getScene();
  63637. if (!scene) {
  63638. return _this;
  63639. }
  63640. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63641. }, this);
  63642. };
  63643. __decorate([
  63644. BABYLON.serialize("rotationY")
  63645. ], CubeTexture.prototype, "_rotationY", void 0);
  63646. return CubeTexture;
  63647. }(BABYLON.BaseTexture));
  63648. BABYLON.CubeTexture = CubeTexture;
  63649. })(BABYLON || (BABYLON = {}));
  63650. //# sourceMappingURL=babylon.cubeTexture.js.map
  63651. var BABYLON;
  63652. (function (BABYLON) {
  63653. var RenderTargetTexture = /** @class */ (function (_super) {
  63654. __extends(RenderTargetTexture, _super);
  63655. /**
  63656. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63657. * or used a shadow, depth texture...
  63658. * @param name The friendly name of the texture
  63659. * @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)
  63660. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63661. * @param generateMipMaps True if mip maps need to be generated after render.
  63662. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63663. * @param type The type of the buffer in the RTT (int, half float, float...)
  63664. * @param isCube True if a cube texture needs to be created
  63665. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63666. * @param generateDepthBuffer True to generate a depth buffer
  63667. * @param generateStencilBuffer True to generate a stencil buffer
  63668. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63669. */
  63670. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63671. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63672. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63673. if (isCube === void 0) { isCube = false; }
  63674. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63675. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63676. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63677. if (isMulti === void 0) { isMulti = false; }
  63678. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63679. _this.isCube = isCube;
  63680. /**
  63681. * Use this list to define the list of mesh you want to render.
  63682. */
  63683. _this.renderList = new Array();
  63684. _this.renderParticles = true;
  63685. _this.renderSprites = false;
  63686. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63687. _this.ignoreCameraViewport = false;
  63688. // Events
  63689. /**
  63690. * An event triggered when the texture is unbind.
  63691. */
  63692. _this.onBeforeBindObservable = new BABYLON.Observable();
  63693. /**
  63694. * An event triggered when the texture is unbind.
  63695. */
  63696. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63697. /**
  63698. * An event triggered before rendering the texture
  63699. */
  63700. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63701. /**
  63702. * An event triggered after rendering the texture
  63703. */
  63704. _this.onAfterRenderObservable = new BABYLON.Observable();
  63705. /**
  63706. * An event triggered after the texture clear
  63707. */
  63708. _this.onClearObservable = new BABYLON.Observable();
  63709. _this._currentRefreshId = -1;
  63710. _this._refreshRate = 1;
  63711. _this._samples = 1;
  63712. /**
  63713. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63714. * It must define where the camera used to render the texture is set
  63715. */
  63716. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63717. scene = _this.getScene();
  63718. if (!scene) {
  63719. return _this;
  63720. }
  63721. _this._engine = scene.getEngine();
  63722. _this.name = name;
  63723. _this.isRenderTarget = true;
  63724. _this._initialSizeParameter = size;
  63725. _this._processSizeParameter(size);
  63726. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63727. });
  63728. _this._generateMipMaps = generateMipMaps ? true : false;
  63729. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63730. // Rendering groups
  63731. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63732. if (isMulti) {
  63733. return _this;
  63734. }
  63735. _this._renderTargetOptions = {
  63736. generateMipMaps: generateMipMaps,
  63737. type: type,
  63738. samplingMode: samplingMode,
  63739. generateDepthBuffer: generateDepthBuffer,
  63740. generateStencilBuffer: generateStencilBuffer
  63741. };
  63742. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63743. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63744. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63745. }
  63746. if (isCube) {
  63747. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63748. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63749. _this._textureMatrix = BABYLON.Matrix.Identity();
  63750. }
  63751. else {
  63752. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63753. }
  63754. return _this;
  63755. }
  63756. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63757. get: function () {
  63758. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63759. },
  63760. enumerable: true,
  63761. configurable: true
  63762. });
  63763. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63764. get: function () {
  63765. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63766. },
  63767. enumerable: true,
  63768. configurable: true
  63769. });
  63770. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63771. get: function () {
  63772. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63773. },
  63774. enumerable: true,
  63775. configurable: true
  63776. });
  63777. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63778. set: function (callback) {
  63779. if (this._onAfterUnbindObserver) {
  63780. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63781. }
  63782. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63783. },
  63784. enumerable: true,
  63785. configurable: true
  63786. });
  63787. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63788. set: function (callback) {
  63789. if (this._onBeforeRenderObserver) {
  63790. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63791. }
  63792. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63793. },
  63794. enumerable: true,
  63795. configurable: true
  63796. });
  63797. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63798. set: function (callback) {
  63799. if (this._onAfterRenderObserver) {
  63800. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63801. }
  63802. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63803. },
  63804. enumerable: true,
  63805. configurable: true
  63806. });
  63807. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63808. set: function (callback) {
  63809. if (this._onClearObserver) {
  63810. this.onClearObservable.remove(this._onClearObserver);
  63811. }
  63812. this._onClearObserver = this.onClearObservable.add(callback);
  63813. },
  63814. enumerable: true,
  63815. configurable: true
  63816. });
  63817. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63818. get: function () {
  63819. return this._renderTargetOptions;
  63820. },
  63821. enumerable: true,
  63822. configurable: true
  63823. });
  63824. RenderTargetTexture.prototype._onRatioRescale = function () {
  63825. if (this._sizeRatio) {
  63826. this.resize(this._initialSizeParameter);
  63827. }
  63828. };
  63829. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63830. get: function () {
  63831. return this._boundingBoxSize;
  63832. },
  63833. /**
  63834. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63835. * When defined, the cubemap will switch to local mode
  63836. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63837. * @example https://www.babylonjs-playground.com/#RNASML
  63838. */
  63839. set: function (value) {
  63840. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63841. return;
  63842. }
  63843. this._boundingBoxSize = value;
  63844. var scene = this.getScene();
  63845. if (scene) {
  63846. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63847. }
  63848. },
  63849. enumerable: true,
  63850. configurable: true
  63851. });
  63852. /**
  63853. * Creates a depth stencil texture.
  63854. * This is only available in WebGL 2 or with the depth texture extension available.
  63855. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63856. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63857. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63858. */
  63859. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63860. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63861. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63862. if (generateStencil === void 0) { generateStencil = false; }
  63863. if (!this.getScene()) {
  63864. return;
  63865. }
  63866. var engine = this.getScene().getEngine();
  63867. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63868. bilinearFiltering: bilinearFiltering,
  63869. comparisonFunction: comparisonFunction,
  63870. generateStencil: generateStencil,
  63871. isCube: this.isCube
  63872. });
  63873. engine.setFrameBufferDepthStencilTexture(this);
  63874. };
  63875. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63876. if (size.ratio) {
  63877. this._sizeRatio = size.ratio;
  63878. this._size = {
  63879. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63880. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63881. };
  63882. }
  63883. else {
  63884. this._size = size;
  63885. }
  63886. };
  63887. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63888. get: function () {
  63889. return this._samples;
  63890. },
  63891. set: function (value) {
  63892. if (this._samples === value) {
  63893. return;
  63894. }
  63895. var scene = this.getScene();
  63896. if (!scene) {
  63897. return;
  63898. }
  63899. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63900. },
  63901. enumerable: true,
  63902. configurable: true
  63903. });
  63904. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63905. this._currentRefreshId = -1;
  63906. };
  63907. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63908. get: function () {
  63909. return this._refreshRate;
  63910. },
  63911. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63912. set: function (value) {
  63913. this._refreshRate = value;
  63914. this.resetRefreshCounter();
  63915. },
  63916. enumerable: true,
  63917. configurable: true
  63918. });
  63919. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63920. if (!this._postProcessManager) {
  63921. var scene = this.getScene();
  63922. if (!scene) {
  63923. return;
  63924. }
  63925. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63926. this._postProcesses = new Array();
  63927. }
  63928. this._postProcesses.push(postProcess);
  63929. this._postProcesses[0].autoClear = false;
  63930. };
  63931. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63932. if (!this._postProcesses) {
  63933. return;
  63934. }
  63935. if (dispose) {
  63936. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63937. var postProcess = _a[_i];
  63938. postProcess.dispose();
  63939. }
  63940. }
  63941. this._postProcesses = [];
  63942. };
  63943. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63944. if (!this._postProcesses) {
  63945. return;
  63946. }
  63947. var index = this._postProcesses.indexOf(postProcess);
  63948. if (index === -1) {
  63949. return;
  63950. }
  63951. this._postProcesses.splice(index, 1);
  63952. if (this._postProcesses.length > 0) {
  63953. this._postProcesses[0].autoClear = false;
  63954. }
  63955. };
  63956. RenderTargetTexture.prototype._shouldRender = function () {
  63957. if (this._currentRefreshId === -1) { // At least render once
  63958. this._currentRefreshId = 1;
  63959. return true;
  63960. }
  63961. if (this.refreshRate === this._currentRefreshId) {
  63962. this._currentRefreshId = 1;
  63963. return true;
  63964. }
  63965. this._currentRefreshId++;
  63966. return false;
  63967. };
  63968. RenderTargetTexture.prototype.getRenderSize = function () {
  63969. if (this._size.width) {
  63970. return this._size.width;
  63971. }
  63972. return this._size;
  63973. };
  63974. RenderTargetTexture.prototype.getRenderWidth = function () {
  63975. if (this._size.width) {
  63976. return this._size.width;
  63977. }
  63978. return this._size;
  63979. };
  63980. RenderTargetTexture.prototype.getRenderHeight = function () {
  63981. if (this._size.width) {
  63982. return this._size.height;
  63983. }
  63984. return this._size;
  63985. };
  63986. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63987. get: function () {
  63988. return true;
  63989. },
  63990. enumerable: true,
  63991. configurable: true
  63992. });
  63993. RenderTargetTexture.prototype.scale = function (ratio) {
  63994. var newSize = this.getRenderSize() * ratio;
  63995. this.resize(newSize);
  63996. };
  63997. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63998. if (this.isCube) {
  63999. return this._textureMatrix;
  64000. }
  64001. return _super.prototype.getReflectionTextureMatrix.call(this);
  64002. };
  64003. RenderTargetTexture.prototype.resize = function (size) {
  64004. this.releaseInternalTexture();
  64005. var scene = this.getScene();
  64006. if (!scene) {
  64007. return;
  64008. }
  64009. this._processSizeParameter(size);
  64010. if (this.isCube) {
  64011. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64012. }
  64013. else {
  64014. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64015. }
  64016. };
  64017. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64018. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64019. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64020. var scene = this.getScene();
  64021. if (!scene) {
  64022. return;
  64023. }
  64024. var engine = scene.getEngine();
  64025. if (this.useCameraPostProcesses !== undefined) {
  64026. useCameraPostProcess = this.useCameraPostProcesses;
  64027. }
  64028. if (this._waitingRenderList) {
  64029. this.renderList = [];
  64030. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64031. var id = this._waitingRenderList[index];
  64032. var mesh_1 = scene.getMeshByID(id);
  64033. if (mesh_1) {
  64034. this.renderList.push(mesh_1);
  64035. }
  64036. }
  64037. delete this._waitingRenderList;
  64038. }
  64039. // Is predicate defined?
  64040. if (this.renderListPredicate) {
  64041. if (this.renderList) {
  64042. this.renderList.splice(0); // Clear previous renderList
  64043. }
  64044. else {
  64045. this.renderList = [];
  64046. }
  64047. var scene = this.getScene();
  64048. if (!scene) {
  64049. return;
  64050. }
  64051. var sceneMeshes = scene.meshes;
  64052. for (var index = 0; index < sceneMeshes.length; index++) {
  64053. var mesh = sceneMeshes[index];
  64054. if (this.renderListPredicate(mesh)) {
  64055. this.renderList.push(mesh);
  64056. }
  64057. }
  64058. }
  64059. this.onBeforeBindObservable.notifyObservers(this);
  64060. // Set custom projection.
  64061. // Needs to be before binding to prevent changing the aspect ratio.
  64062. var camera;
  64063. if (this.activeCamera) {
  64064. camera = this.activeCamera;
  64065. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64066. if (this.activeCamera !== scene.activeCamera) {
  64067. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64068. }
  64069. }
  64070. else {
  64071. camera = scene.activeCamera;
  64072. if (camera) {
  64073. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64074. }
  64075. }
  64076. // Prepare renderingManager
  64077. this._renderingManager.reset();
  64078. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64079. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64080. var sceneRenderId = scene.getRenderId();
  64081. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64082. var mesh = currentRenderList[meshIndex];
  64083. if (mesh) {
  64084. if (!mesh.isReady(this.refreshRate === 0)) {
  64085. this.resetRefreshCounter();
  64086. continue;
  64087. }
  64088. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64089. var isMasked = void 0;
  64090. if (!this.renderList && camera) {
  64091. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64092. }
  64093. else {
  64094. isMasked = false;
  64095. }
  64096. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64097. mesh._activate(sceneRenderId);
  64098. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64099. var subMesh = mesh.subMeshes[subIndex];
  64100. scene._activeIndices.addCount(subMesh.indexCount, false);
  64101. this._renderingManager.dispatch(subMesh, mesh);
  64102. }
  64103. }
  64104. }
  64105. }
  64106. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64107. var particleSystem = scene.particleSystems[particleIndex];
  64108. var emitter = particleSystem.emitter;
  64109. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64110. continue;
  64111. }
  64112. if (currentRenderList.indexOf(emitter) >= 0) {
  64113. this._renderingManager.dispatchParticles(particleSystem);
  64114. }
  64115. }
  64116. if (this.isCube) {
  64117. for (var face = 0; face < 6; face++) {
  64118. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64119. scene.incrementRenderId();
  64120. scene.resetCachedMaterial();
  64121. }
  64122. }
  64123. else {
  64124. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64125. }
  64126. this.onAfterUnbindObservable.notifyObservers(this);
  64127. if (scene.activeCamera) {
  64128. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64129. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64130. }
  64131. engine.setViewport(scene.activeCamera.viewport);
  64132. }
  64133. scene.resetCachedMaterial();
  64134. };
  64135. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64136. var minimum = 128;
  64137. var x = renderDimension * scale;
  64138. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64139. // Ensure we don't exceed the render dimension (while staying POT)
  64140. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64141. };
  64142. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64143. var _this = this;
  64144. if (!this._texture) {
  64145. return;
  64146. }
  64147. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64148. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64149. });
  64150. };
  64151. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64152. var scene = this.getScene();
  64153. if (!scene) {
  64154. return;
  64155. }
  64156. var engine = scene.getEngine();
  64157. if (!this._texture) {
  64158. return;
  64159. }
  64160. // Bind
  64161. if (this._postProcessManager) {
  64162. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64163. }
  64164. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64165. if (this._texture) {
  64166. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64167. }
  64168. }
  64169. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64170. // Clear
  64171. if (this.onClearObservable.hasObservers()) {
  64172. this.onClearObservable.notifyObservers(engine);
  64173. }
  64174. else {
  64175. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64176. }
  64177. if (!this._doNotChangeAspectRatio) {
  64178. scene.updateTransformMatrix(true);
  64179. }
  64180. // Render
  64181. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64182. if (this._postProcessManager) {
  64183. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64184. }
  64185. else if (useCameraPostProcess) {
  64186. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64187. }
  64188. if (!this._doNotChangeAspectRatio) {
  64189. scene.updateTransformMatrix(true);
  64190. }
  64191. // Dump ?
  64192. if (dumpForDebug) {
  64193. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64194. }
  64195. // Unbind
  64196. if (!this.isCube || faceIndex === 5) {
  64197. if (this.isCube) {
  64198. if (faceIndex === 5) {
  64199. engine.generateMipMapsForCubemap(this._texture);
  64200. }
  64201. }
  64202. this.unbindFrameBuffer(engine, faceIndex);
  64203. }
  64204. else {
  64205. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64206. }
  64207. };
  64208. /**
  64209. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64210. * This allowed control for front to back rendering or reversly depending of the special needs.
  64211. *
  64212. * @param renderingGroupId The rendering group id corresponding to its index
  64213. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64214. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64215. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64216. */
  64217. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64218. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64219. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64220. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64221. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64222. };
  64223. /**
  64224. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64225. *
  64226. * @param renderingGroupId The rendering group id corresponding to its index
  64227. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64228. */
  64229. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64230. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64231. };
  64232. RenderTargetTexture.prototype.clone = function () {
  64233. var textureSize = this.getSize();
  64234. 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);
  64235. // Base texture
  64236. newTexture.hasAlpha = this.hasAlpha;
  64237. newTexture.level = this.level;
  64238. // RenderTarget Texture
  64239. newTexture.coordinatesMode = this.coordinatesMode;
  64240. if (this.renderList) {
  64241. newTexture.renderList = this.renderList.slice(0);
  64242. }
  64243. return newTexture;
  64244. };
  64245. RenderTargetTexture.prototype.serialize = function () {
  64246. if (!this.name) {
  64247. return null;
  64248. }
  64249. var serializationObject = _super.prototype.serialize.call(this);
  64250. serializationObject.renderTargetSize = this.getRenderSize();
  64251. serializationObject.renderList = [];
  64252. if (this.renderList) {
  64253. for (var index = 0; index < this.renderList.length; index++) {
  64254. serializationObject.renderList.push(this.renderList[index].id);
  64255. }
  64256. }
  64257. return serializationObject;
  64258. };
  64259. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64260. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64261. var objBuffer = this.getInternalTexture();
  64262. var scene = this.getScene();
  64263. if (objBuffer && scene) {
  64264. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64265. }
  64266. };
  64267. RenderTargetTexture.prototype.dispose = function () {
  64268. if (this._postProcessManager) {
  64269. this._postProcessManager.dispose();
  64270. this._postProcessManager = null;
  64271. }
  64272. this.clearPostProcesses(true);
  64273. if (this._resizeObserver) {
  64274. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64275. this._resizeObserver = null;
  64276. }
  64277. this.renderList = null;
  64278. // Remove from custom render targets
  64279. var scene = this.getScene();
  64280. if (!scene) {
  64281. return;
  64282. }
  64283. var index = scene.customRenderTargets.indexOf(this);
  64284. if (index >= 0) {
  64285. scene.customRenderTargets.splice(index, 1);
  64286. }
  64287. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64288. var camera = _a[_i];
  64289. index = camera.customRenderTargets.indexOf(this);
  64290. if (index >= 0) {
  64291. camera.customRenderTargets.splice(index, 1);
  64292. }
  64293. }
  64294. _super.prototype.dispose.call(this);
  64295. };
  64296. RenderTargetTexture.prototype._rebuild = function () {
  64297. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64298. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64299. }
  64300. if (this._postProcessManager) {
  64301. this._postProcessManager._rebuild();
  64302. }
  64303. };
  64304. /**
  64305. * Clear the info related to rendering groups preventing retention point in material dispose.
  64306. */
  64307. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64308. if (this._renderingManager) {
  64309. this._renderingManager.freeRenderingGroups();
  64310. }
  64311. };
  64312. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64313. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64314. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64315. return RenderTargetTexture;
  64316. }(BABYLON.Texture));
  64317. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64318. })(BABYLON || (BABYLON = {}));
  64319. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64320. var BABYLON;
  64321. (function (BABYLON) {
  64322. ;
  64323. var MultiRenderTarget = /** @class */ (function (_super) {
  64324. __extends(MultiRenderTarget, _super);
  64325. function MultiRenderTarget(name, size, count, scene, options) {
  64326. var _this = this;
  64327. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64328. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64329. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64330. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64331. _this._engine = scene.getEngine();
  64332. if (!_this.isSupported) {
  64333. _this.dispose();
  64334. return;
  64335. }
  64336. var types = [];
  64337. var samplingModes = [];
  64338. for (var i = 0; i < count; i++) {
  64339. if (options && options.types && options.types[i] !== undefined) {
  64340. types.push(options.types[i]);
  64341. }
  64342. else {
  64343. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64344. }
  64345. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64346. samplingModes.push(options.samplingModes[i]);
  64347. }
  64348. else {
  64349. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64350. }
  64351. }
  64352. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64353. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64354. _this._size = size;
  64355. _this._multiRenderTargetOptions = {
  64356. samplingModes: samplingModes,
  64357. generateMipMaps: generateMipMaps,
  64358. generateDepthBuffer: generateDepthBuffer,
  64359. generateStencilBuffer: generateStencilBuffer,
  64360. generateDepthTexture: generateDepthTexture,
  64361. types: types,
  64362. textureCount: count
  64363. };
  64364. _this._createInternalTextures();
  64365. _this._createTextures();
  64366. return _this;
  64367. }
  64368. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64369. get: function () {
  64370. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64371. },
  64372. enumerable: true,
  64373. configurable: true
  64374. });
  64375. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64376. get: function () {
  64377. return this._textures;
  64378. },
  64379. enumerable: true,
  64380. configurable: true
  64381. });
  64382. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64383. get: function () {
  64384. return this._textures[this._textures.length - 1];
  64385. },
  64386. enumerable: true,
  64387. configurable: true
  64388. });
  64389. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64390. set: function (wrap) {
  64391. if (this._textures) {
  64392. for (var i = 0; i < this._textures.length; i++) {
  64393. this._textures[i].wrapU = wrap;
  64394. }
  64395. }
  64396. },
  64397. enumerable: true,
  64398. configurable: true
  64399. });
  64400. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64401. set: function (wrap) {
  64402. if (this._textures) {
  64403. for (var i = 0; i < this._textures.length; i++) {
  64404. this._textures[i].wrapV = wrap;
  64405. }
  64406. }
  64407. },
  64408. enumerable: true,
  64409. configurable: true
  64410. });
  64411. MultiRenderTarget.prototype._rebuild = function () {
  64412. this.releaseInternalTextures();
  64413. this._createInternalTextures();
  64414. for (var i = 0; i < this._internalTextures.length; i++) {
  64415. var texture = this._textures[i];
  64416. texture._texture = this._internalTextures[i];
  64417. }
  64418. // Keeps references to frame buffer and stencil/depth buffer
  64419. this._texture = this._internalTextures[0];
  64420. };
  64421. MultiRenderTarget.prototype._createInternalTextures = function () {
  64422. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64423. };
  64424. MultiRenderTarget.prototype._createTextures = function () {
  64425. this._textures = [];
  64426. for (var i = 0; i < this._internalTextures.length; i++) {
  64427. var texture = new BABYLON.Texture(null, this.getScene());
  64428. texture._texture = this._internalTextures[i];
  64429. this._textures.push(texture);
  64430. }
  64431. // Keeps references to frame buffer and stencil/depth buffer
  64432. this._texture = this._internalTextures[0];
  64433. };
  64434. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64435. get: function () {
  64436. return this._samples;
  64437. },
  64438. set: function (value) {
  64439. if (this._samples === value) {
  64440. return;
  64441. }
  64442. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64443. },
  64444. enumerable: true,
  64445. configurable: true
  64446. });
  64447. MultiRenderTarget.prototype.resize = function (size) {
  64448. this.releaseInternalTextures();
  64449. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64450. this._createInternalTextures();
  64451. };
  64452. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64453. var _this = this;
  64454. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64455. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64456. });
  64457. };
  64458. MultiRenderTarget.prototype.dispose = function () {
  64459. this.releaseInternalTextures();
  64460. _super.prototype.dispose.call(this);
  64461. };
  64462. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64463. if (!this._internalTextures) {
  64464. return;
  64465. }
  64466. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64467. if (this._internalTextures[i] !== undefined) {
  64468. this._internalTextures[i].dispose();
  64469. this._internalTextures.splice(i, 1);
  64470. }
  64471. }
  64472. };
  64473. return MultiRenderTarget;
  64474. }(BABYLON.RenderTargetTexture));
  64475. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64476. })(BABYLON || (BABYLON = {}));
  64477. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64478. var BABYLON;
  64479. (function (BABYLON) {
  64480. var MirrorTexture = /** @class */ (function (_super) {
  64481. __extends(MirrorTexture, _super);
  64482. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64483. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64484. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64485. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64486. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64487. _this.scene = scene;
  64488. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64489. _this._transformMatrix = BABYLON.Matrix.Zero();
  64490. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64491. _this._adaptiveBlurKernel = 0;
  64492. _this._blurKernelX = 0;
  64493. _this._blurKernelY = 0;
  64494. _this._blurRatio = 1.0;
  64495. _this.ignoreCameraViewport = true;
  64496. _this._updateGammaSpace();
  64497. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64498. _this._updateGammaSpace;
  64499. });
  64500. _this.onBeforeRenderObservable.add(function () {
  64501. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64502. _this._savedViewMatrix = scene.getViewMatrix();
  64503. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64504. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64505. scene.clipPlane = _this.mirrorPlane;
  64506. scene.getEngine().cullBackFaces = false;
  64507. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64508. });
  64509. _this.onAfterRenderObservable.add(function () {
  64510. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64511. scene.getEngine().cullBackFaces = true;
  64512. scene._mirroredCameraPosition = null;
  64513. delete scene.clipPlane;
  64514. });
  64515. return _this;
  64516. }
  64517. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64518. get: function () {
  64519. return this._blurRatio;
  64520. },
  64521. set: function (value) {
  64522. if (this._blurRatio === value) {
  64523. return;
  64524. }
  64525. this._blurRatio = value;
  64526. this._preparePostProcesses();
  64527. },
  64528. enumerable: true,
  64529. configurable: true
  64530. });
  64531. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64532. set: function (value) {
  64533. this._adaptiveBlurKernel = value;
  64534. this._autoComputeBlurKernel();
  64535. },
  64536. enumerable: true,
  64537. configurable: true
  64538. });
  64539. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64540. set: function (value) {
  64541. this.blurKernelX = value;
  64542. this.blurKernelY = value;
  64543. },
  64544. enumerable: true,
  64545. configurable: true
  64546. });
  64547. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64548. get: function () {
  64549. return this._blurKernelX;
  64550. },
  64551. set: function (value) {
  64552. if (this._blurKernelX === value) {
  64553. return;
  64554. }
  64555. this._blurKernelX = value;
  64556. this._preparePostProcesses();
  64557. },
  64558. enumerable: true,
  64559. configurable: true
  64560. });
  64561. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64562. get: function () {
  64563. return this._blurKernelY;
  64564. },
  64565. set: function (value) {
  64566. if (this._blurKernelY === value) {
  64567. return;
  64568. }
  64569. this._blurKernelY = value;
  64570. this._preparePostProcesses();
  64571. },
  64572. enumerable: true,
  64573. configurable: true
  64574. });
  64575. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64576. var engine = this.getScene().getEngine();
  64577. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64578. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64579. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64580. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64581. };
  64582. MirrorTexture.prototype._onRatioRescale = function () {
  64583. if (this._sizeRatio) {
  64584. this.resize(this._initialSizeParameter);
  64585. if (!this._adaptiveBlurKernel) {
  64586. this._preparePostProcesses();
  64587. }
  64588. }
  64589. if (this._adaptiveBlurKernel) {
  64590. this._autoComputeBlurKernel();
  64591. }
  64592. };
  64593. MirrorTexture.prototype._updateGammaSpace = function () {
  64594. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64595. };
  64596. MirrorTexture.prototype._preparePostProcesses = function () {
  64597. this.clearPostProcesses(true);
  64598. if (this._blurKernelX && this._blurKernelY) {
  64599. var engine = this.getScene().getEngine();
  64600. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64601. 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);
  64602. this._blurX.autoClear = false;
  64603. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64604. this._blurX.inputTexture = this._texture;
  64605. }
  64606. else {
  64607. this._blurX.alwaysForcePOT = true;
  64608. }
  64609. 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);
  64610. this._blurY.autoClear = false;
  64611. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64612. this.addPostProcess(this._blurX);
  64613. this.addPostProcess(this._blurY);
  64614. }
  64615. else {
  64616. if (this._blurY) {
  64617. this.removePostProcess(this._blurY);
  64618. this._blurY.dispose();
  64619. this._blurY = null;
  64620. }
  64621. if (this._blurX) {
  64622. this.removePostProcess(this._blurX);
  64623. this._blurX.dispose();
  64624. this._blurX = null;
  64625. }
  64626. }
  64627. };
  64628. MirrorTexture.prototype.clone = function () {
  64629. var scene = this.getScene();
  64630. if (!scene) {
  64631. return this;
  64632. }
  64633. var textureSize = this.getSize();
  64634. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64635. // Base texture
  64636. newTexture.hasAlpha = this.hasAlpha;
  64637. newTexture.level = this.level;
  64638. // Mirror Texture
  64639. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64640. if (this.renderList) {
  64641. newTexture.renderList = this.renderList.slice(0);
  64642. }
  64643. return newTexture;
  64644. };
  64645. MirrorTexture.prototype.serialize = function () {
  64646. if (!this.name) {
  64647. return null;
  64648. }
  64649. var serializationObject = _super.prototype.serialize.call(this);
  64650. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64651. return serializationObject;
  64652. };
  64653. MirrorTexture.prototype.dispose = function () {
  64654. _super.prototype.dispose.call(this);
  64655. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64656. };
  64657. return MirrorTexture;
  64658. }(BABYLON.RenderTargetTexture));
  64659. BABYLON.MirrorTexture = MirrorTexture;
  64660. })(BABYLON || (BABYLON = {}));
  64661. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64662. var BABYLON;
  64663. (function (BABYLON) {
  64664. /**
  64665. * Creates a refraction texture used by refraction channel of the standard material.
  64666. * @param name the texture name
  64667. * @param size size of the underlying texture
  64668. * @param scene root scene
  64669. */
  64670. var RefractionTexture = /** @class */ (function (_super) {
  64671. __extends(RefractionTexture, _super);
  64672. function RefractionTexture(name, size, scene, generateMipMaps) {
  64673. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64674. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64675. _this.depth = 2.0;
  64676. _this.onBeforeRenderObservable.add(function () {
  64677. scene.clipPlane = _this.refractionPlane;
  64678. });
  64679. _this.onAfterRenderObservable.add(function () {
  64680. delete scene.clipPlane;
  64681. });
  64682. return _this;
  64683. }
  64684. RefractionTexture.prototype.clone = function () {
  64685. var scene = this.getScene();
  64686. if (!scene) {
  64687. return this;
  64688. }
  64689. var textureSize = this.getSize();
  64690. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64691. // Base texture
  64692. newTexture.hasAlpha = this.hasAlpha;
  64693. newTexture.level = this.level;
  64694. // Refraction Texture
  64695. newTexture.refractionPlane = this.refractionPlane.clone();
  64696. if (this.renderList) {
  64697. newTexture.renderList = this.renderList.slice(0);
  64698. }
  64699. newTexture.depth = this.depth;
  64700. return newTexture;
  64701. };
  64702. RefractionTexture.prototype.serialize = function () {
  64703. if (!this.name) {
  64704. return null;
  64705. }
  64706. var serializationObject = _super.prototype.serialize.call(this);
  64707. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64708. serializationObject.depth = this.depth;
  64709. return serializationObject;
  64710. };
  64711. return RefractionTexture;
  64712. }(BABYLON.RenderTargetTexture));
  64713. BABYLON.RefractionTexture = RefractionTexture;
  64714. })(BABYLON || (BABYLON = {}));
  64715. //# sourceMappingURL=babylon.refractionTexture.js.map
  64716. var BABYLON;
  64717. (function (BABYLON) {
  64718. /**
  64719. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64720. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64721. */
  64722. var DynamicTexture = /** @class */ (function (_super) {
  64723. __extends(DynamicTexture, _super);
  64724. /**
  64725. * Creates a {BABYLON.DynamicTexture}
  64726. * @param name defines the name of the texture
  64727. * @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
  64728. * @param scene defines the scene where you want the texture
  64729. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64730. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64731. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64732. */
  64733. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64734. if (scene === void 0) { scene = null; }
  64735. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64736. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64737. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64738. _this.name = name;
  64739. _this._engine = _this.getScene().getEngine();
  64740. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64741. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64742. _this._generateMipMaps = generateMipMaps;
  64743. if (options.getContext) {
  64744. _this._canvas = options;
  64745. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64746. }
  64747. else {
  64748. _this._canvas = document.createElement("canvas");
  64749. if (options.width || options.width === 0) {
  64750. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64751. }
  64752. else {
  64753. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64754. }
  64755. }
  64756. var textureSize = _this.getSize();
  64757. _this._canvas.width = textureSize.width;
  64758. _this._canvas.height = textureSize.height;
  64759. _this._context = _this._canvas.getContext("2d");
  64760. return _this;
  64761. }
  64762. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64763. /**
  64764. * Gets the current state of canRescale
  64765. */
  64766. get: function () {
  64767. return true;
  64768. },
  64769. enumerable: true,
  64770. configurable: true
  64771. });
  64772. DynamicTexture.prototype._recreate = function (textureSize) {
  64773. this._canvas.width = textureSize.width;
  64774. this._canvas.height = textureSize.height;
  64775. this.releaseInternalTexture();
  64776. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64777. };
  64778. /**
  64779. * Scales the texture
  64780. * @param ratio the scale factor to apply to both width and height
  64781. */
  64782. DynamicTexture.prototype.scale = function (ratio) {
  64783. var textureSize = this.getSize();
  64784. textureSize.width *= ratio;
  64785. textureSize.height *= ratio;
  64786. this._recreate(textureSize);
  64787. };
  64788. /**
  64789. * Resizes the texture
  64790. * @param width the new width
  64791. * @param height the new height
  64792. */
  64793. DynamicTexture.prototype.scaleTo = function (width, height) {
  64794. var textureSize = this.getSize();
  64795. textureSize.width = width;
  64796. textureSize.height = height;
  64797. this._recreate(textureSize);
  64798. };
  64799. /**
  64800. * Gets the context of the canvas used by the texture
  64801. * @returns the canvas context of the dynamic texture
  64802. */
  64803. DynamicTexture.prototype.getContext = function () {
  64804. return this._context;
  64805. };
  64806. /**
  64807. * Clears the texture
  64808. */
  64809. DynamicTexture.prototype.clear = function () {
  64810. var size = this.getSize();
  64811. this._context.fillRect(0, 0, size.width, size.height);
  64812. };
  64813. /**
  64814. * Updates the texture
  64815. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64816. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64817. */
  64818. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64819. if (premulAlpha === void 0) { premulAlpha = false; }
  64820. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64821. };
  64822. /**
  64823. * Draws text onto the texture
  64824. * @param text defines the text to be drawn
  64825. * @param x defines the placement of the text from the left
  64826. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64827. * @param font defines the font to be used with font-style, font-size, font-name
  64828. * @param color defines the color used for the text
  64829. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64830. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64831. * @param update defines whether texture is immediately update (default is true)
  64832. */
  64833. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64834. if (update === void 0) { update = true; }
  64835. var size = this.getSize();
  64836. if (clearColor) {
  64837. this._context.fillStyle = clearColor;
  64838. this._context.fillRect(0, 0, size.width, size.height);
  64839. }
  64840. this._context.font = font;
  64841. if (x === null || x === undefined) {
  64842. var textSize = this._context.measureText(text);
  64843. x = (size.width - textSize.width) / 2;
  64844. }
  64845. if (y === null || y === undefined) {
  64846. var fontSize = parseInt((font.replace(/\D/g, '')));
  64847. y = (size.height / 2) + (fontSize / 3.65);
  64848. }
  64849. this._context.fillStyle = color;
  64850. this._context.fillText(text, x, y);
  64851. if (update) {
  64852. this.update(invertY);
  64853. }
  64854. };
  64855. /**
  64856. * Clones the texture
  64857. * @returns the clone of the texture.
  64858. */
  64859. DynamicTexture.prototype.clone = function () {
  64860. var scene = this.getScene();
  64861. if (!scene) {
  64862. return this;
  64863. }
  64864. var textureSize = this.getSize();
  64865. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64866. // Base texture
  64867. newTexture.hasAlpha = this.hasAlpha;
  64868. newTexture.level = this.level;
  64869. // Dynamic Texture
  64870. newTexture.wrapU = this.wrapU;
  64871. newTexture.wrapV = this.wrapV;
  64872. return newTexture;
  64873. };
  64874. /** @hidden */
  64875. DynamicTexture.prototype._rebuild = function () {
  64876. this.update();
  64877. };
  64878. return DynamicTexture;
  64879. }(BABYLON.Texture));
  64880. BABYLON.DynamicTexture = DynamicTexture;
  64881. })(BABYLON || (BABYLON = {}));
  64882. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64883. var BABYLON;
  64884. (function (BABYLON) {
  64885. var VideoTexture = /** @class */ (function (_super) {
  64886. __extends(VideoTexture, _super);
  64887. /**
  64888. * Creates a video texture.
  64889. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64890. * @param {string | null} name optional name, will detect from video source, if not defined
  64891. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64892. * @param {BABYLON.Scene} scene is obviously the current scene.
  64893. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64894. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64895. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64896. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64897. */
  64898. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64899. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64900. if (invertY === void 0) { invertY = false; }
  64901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64902. if (settings === void 0) { settings = {
  64903. autoPlay: true,
  64904. loop: true,
  64905. autoUpdateTexture: true,
  64906. }; }
  64907. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64908. _this._stillImageCaptured = false;
  64909. _this._createInternalTexture = function () {
  64910. if (_this._texture != null) {
  64911. return;
  64912. }
  64913. if (!_this._engine.needPOTTextures ||
  64914. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64915. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64916. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64917. }
  64918. else {
  64919. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64920. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64921. _this._generateMipMaps = false;
  64922. }
  64923. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64924. if (!_this.video.autoplay) {
  64925. var oldHandler_1 = _this.video.onplaying;
  64926. _this.video.onplaying = function () {
  64927. _this.video.onplaying = oldHandler_1;
  64928. _this._texture.isReady = true;
  64929. _this._updateInternalTexture();
  64930. _this.video.pause();
  64931. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64932. _this.onLoadObservable.notifyObservers(_this);
  64933. }
  64934. };
  64935. _this.video.play();
  64936. }
  64937. else {
  64938. _this._texture.isReady = true;
  64939. _this._updateInternalTexture();
  64940. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64941. _this.onLoadObservable.notifyObservers(_this);
  64942. }
  64943. }
  64944. };
  64945. _this.reset = function () {
  64946. if (_this._texture == null) {
  64947. return;
  64948. }
  64949. _this._texture.dispose();
  64950. _this._texture = null;
  64951. };
  64952. _this._updateInternalTexture = function (e) {
  64953. if (_this._texture == null || !_this._texture.isReady) {
  64954. return;
  64955. }
  64956. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64957. return;
  64958. }
  64959. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64960. };
  64961. _this._engine = _this.getScene().getEngine();
  64962. _this._generateMipMaps = generateMipMaps;
  64963. _this._samplingMode = samplingMode;
  64964. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64965. _this.name = name || _this._getName(src);
  64966. _this.video = _this._getVideo(src);
  64967. if (settings.autoPlay !== undefined) {
  64968. _this.video.autoplay = settings.autoPlay;
  64969. }
  64970. if (settings.loop !== undefined) {
  64971. _this.video.loop = settings.loop;
  64972. }
  64973. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64974. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64975. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64976. _this.video.addEventListener("emptied", _this.reset);
  64977. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64978. _this._createInternalTexture();
  64979. }
  64980. return _this;
  64981. }
  64982. VideoTexture.prototype._getName = function (src) {
  64983. if (src instanceof HTMLVideoElement) {
  64984. return src.currentSrc;
  64985. }
  64986. if (typeof src === "object") {
  64987. return src.toString();
  64988. }
  64989. return src;
  64990. };
  64991. ;
  64992. VideoTexture.prototype._getVideo = function (src) {
  64993. if (src instanceof HTMLVideoElement) {
  64994. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64995. return src;
  64996. }
  64997. var video = document.createElement("video");
  64998. if (typeof src === "string") {
  64999. BABYLON.Tools.SetCorsBehavior(src, video);
  65000. video.src = src;
  65001. }
  65002. else {
  65003. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65004. src.forEach(function (url) {
  65005. var source = document.createElement("source");
  65006. source.src = url;
  65007. video.appendChild(source);
  65008. });
  65009. }
  65010. return video;
  65011. };
  65012. ;
  65013. /**
  65014. * Internal method to initiate `update`.
  65015. */
  65016. VideoTexture.prototype._rebuild = function () {
  65017. this.update();
  65018. };
  65019. /**
  65020. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65021. */
  65022. VideoTexture.prototype.update = function () {
  65023. if (!this.autoUpdateTexture) {
  65024. // Expecting user to call `updateTexture` manually
  65025. return;
  65026. }
  65027. this.updateTexture(true);
  65028. };
  65029. /**
  65030. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65031. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65032. */
  65033. VideoTexture.prototype.updateTexture = function (isVisible) {
  65034. if (!isVisible) {
  65035. return;
  65036. }
  65037. if (this.video.paused && this._stillImageCaptured) {
  65038. return;
  65039. }
  65040. this._stillImageCaptured = true;
  65041. this._updateInternalTexture();
  65042. };
  65043. /**
  65044. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65045. * @param url New url.
  65046. */
  65047. VideoTexture.prototype.updateURL = function (url) {
  65048. this.video.src = url;
  65049. };
  65050. VideoTexture.prototype.dispose = function () {
  65051. _super.prototype.dispose.call(this);
  65052. this.video.removeEventListener("canplay", this._createInternalTexture);
  65053. this.video.removeEventListener("paused", this._updateInternalTexture);
  65054. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65055. this.video.removeEventListener("emptied", this.reset);
  65056. this.video.pause();
  65057. };
  65058. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65059. var video = document.createElement("video");
  65060. var constraintsDeviceId;
  65061. if (constraints && constraints.deviceId) {
  65062. constraintsDeviceId = {
  65063. exact: constraints.deviceId,
  65064. };
  65065. }
  65066. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65067. if (navigator.mediaDevices) {
  65068. navigator.mediaDevices.getUserMedia({ video: constraints })
  65069. .then(function (stream) {
  65070. if (video.mozSrcObject !== undefined) {
  65071. // hack for Firefox < 19
  65072. video.mozSrcObject = stream;
  65073. }
  65074. else {
  65075. video.srcObject = stream;
  65076. }
  65077. var onPlaying = function () {
  65078. if (onReady) {
  65079. onReady(new VideoTexture("video", video, scene, true, true));
  65080. }
  65081. video.removeEventListener("playing", onPlaying);
  65082. };
  65083. video.addEventListener("playing", onPlaying);
  65084. video.play();
  65085. })
  65086. .catch(function (err) {
  65087. BABYLON.Tools.Error(err.name);
  65088. });
  65089. }
  65090. else {
  65091. navigator.getUserMedia =
  65092. navigator.getUserMedia ||
  65093. navigator.webkitGetUserMedia ||
  65094. navigator.mozGetUserMedia ||
  65095. navigator.msGetUserMedia;
  65096. if (navigator.getUserMedia) {
  65097. navigator.getUserMedia({
  65098. video: {
  65099. deviceId: constraintsDeviceId,
  65100. width: {
  65101. min: (constraints && constraints.minWidth) || 256,
  65102. max: (constraints && constraints.maxWidth) || 640,
  65103. },
  65104. height: {
  65105. min: (constraints && constraints.minHeight) || 256,
  65106. max: (constraints && constraints.maxHeight) || 480,
  65107. },
  65108. },
  65109. }, function (stream) {
  65110. if (video.mozSrcObject !== undefined) {
  65111. // hack for Firefox < 19
  65112. video.mozSrcObject = stream;
  65113. }
  65114. else {
  65115. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65116. }
  65117. video.play();
  65118. if (onReady) {
  65119. onReady(new VideoTexture("video", video, scene, true, true));
  65120. }
  65121. }, function (e) {
  65122. BABYLON.Tools.Error(e.name);
  65123. });
  65124. }
  65125. }
  65126. };
  65127. return VideoTexture;
  65128. }(BABYLON.Texture));
  65129. BABYLON.VideoTexture = VideoTexture;
  65130. })(BABYLON || (BABYLON = {}));
  65131. //# sourceMappingURL=babylon.videoTexture.js.map
  65132. var BABYLON;
  65133. (function (BABYLON) {
  65134. var RawTexture = /** @class */ (function (_super) {
  65135. __extends(RawTexture, _super);
  65136. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65137. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65138. if (invertY === void 0) { invertY = false; }
  65139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65140. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65141. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65142. _this.format = format;
  65143. _this._engine = scene.getEngine();
  65144. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65145. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65146. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65147. return _this;
  65148. }
  65149. RawTexture.prototype.update = function (data) {
  65150. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65151. };
  65152. // Statics
  65153. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65154. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65155. if (invertY === void 0) { invertY = false; }
  65156. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65157. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65158. };
  65159. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65160. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65161. if (invertY === void 0) { invertY = false; }
  65162. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65163. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65164. };
  65165. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65166. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65167. if (invertY === void 0) { invertY = false; }
  65168. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65169. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65170. };
  65171. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65172. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65173. if (invertY === void 0) { invertY = false; }
  65174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65175. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65176. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65177. };
  65178. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65179. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65180. if (invertY === void 0) { invertY = false; }
  65181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65182. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65183. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65184. };
  65185. return RawTexture;
  65186. }(BABYLON.Texture));
  65187. BABYLON.RawTexture = RawTexture;
  65188. })(BABYLON || (BABYLON = {}));
  65189. //# sourceMappingURL=babylon.rawTexture.js.map
  65190. var BABYLON;
  65191. (function (BABYLON) {
  65192. /**
  65193. * Class used to store 3D textures containing user data
  65194. */
  65195. var RawTexture3D = /** @class */ (function (_super) {
  65196. __extends(RawTexture3D, _super);
  65197. /**
  65198. * Create a new RawTexture3D
  65199. * @param data defines the data of the texture
  65200. * @param width defines the width of the texture
  65201. * @param height defines the height of the texture
  65202. * @param depth defines the depth of the texture
  65203. * @param format defines the texture format to use
  65204. * @param scene defines the hosting scene
  65205. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65206. * @param invertY defines if texture must be stored with Y axis inverted
  65207. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65208. */
  65209. function RawTexture3D(data, width, height, depth,
  65210. /** Gets or sets the texture format to use*/
  65211. format, scene, generateMipMaps, invertY, samplingMode) {
  65212. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65213. if (invertY === void 0) { invertY = false; }
  65214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65215. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65216. _this.format = format;
  65217. _this._engine = scene.getEngine();
  65218. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  65219. _this.is3D = true;
  65220. return _this;
  65221. }
  65222. /**
  65223. * Update the texture with new data
  65224. * @param data defines the data to store in the texture
  65225. */
  65226. RawTexture3D.prototype.update = function (data) {
  65227. if (!this._texture) {
  65228. return;
  65229. }
  65230. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  65231. };
  65232. return RawTexture3D;
  65233. }(BABYLON.Texture));
  65234. BABYLON.RawTexture3D = RawTexture3D;
  65235. })(BABYLON || (BABYLON = {}));
  65236. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65237. var BABYLON;
  65238. (function (BABYLON) {
  65239. /**
  65240. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65241. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65242. */
  65243. var PostProcess = /** @class */ (function () {
  65244. /**
  65245. * Creates a new instance PostProcess
  65246. * @param name The name of the PostProcess.
  65247. * @param fragmentUrl The url of the fragment shader to be used.
  65248. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65249. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65250. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65251. * @param camera The camera to apply the render pass to.
  65252. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65253. * @param engine The engine which the post process will be applied. (default: current engine)
  65254. * @param reusable If the post process can be reused on the same frame. (default: false)
  65255. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65256. * @param textureType Type of textures used when performing the post process. (default: 0)
  65257. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65258. * @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
  65259. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65260. */
  65261. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65262. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65263. if (defines === void 0) { defines = null; }
  65264. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65265. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65266. if (blockCompilation === void 0) { blockCompilation = false; }
  65267. this.name = name;
  65268. /**
  65269. * Width of the texture to apply the post process on
  65270. */
  65271. this.width = -1;
  65272. /**
  65273. * Height of the texture to apply the post process on
  65274. */
  65275. this.height = -1;
  65276. /**
  65277. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65278. */
  65279. this._outputTexture = null;
  65280. /**
  65281. * If the buffer needs to be cleared before applying the post process. (default: true)
  65282. * Should be set to false if shader will overwrite all previous pixels.
  65283. */
  65284. this.autoClear = true;
  65285. /**
  65286. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65287. */
  65288. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65289. /**
  65290. * Animations to be used for the post processing
  65291. */
  65292. this.animations = new Array();
  65293. /**
  65294. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65295. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65296. */
  65297. this.enablePixelPerfectMode = false;
  65298. /**
  65299. * Force the postprocess to be applied without taking in account viewport
  65300. */
  65301. this.forceFullscreenViewport = true;
  65302. /**
  65303. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65304. */
  65305. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65306. /**
  65307. * Force textures to be a power of two (default: false)
  65308. */
  65309. this.alwaysForcePOT = false;
  65310. /**
  65311. * Number of sample textures (default: 1)
  65312. */
  65313. this.samples = 1;
  65314. /**
  65315. * Modify the scale of the post process to be the same as the viewport (default: false)
  65316. */
  65317. this.adaptScaleToCurrentViewport = false;
  65318. this._reusable = false;
  65319. /**
  65320. * Smart array of input and output textures for the post process.
  65321. */
  65322. this._textures = new BABYLON.SmartArray(2);
  65323. /**
  65324. * The index in _textures that corresponds to the output texture.
  65325. */
  65326. this._currentRenderTextureInd = 0;
  65327. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65328. this._texelSize = BABYLON.Vector2.Zero();
  65329. // Events
  65330. /**
  65331. * An event triggered when the postprocess is activated.
  65332. */
  65333. this.onActivateObservable = new BABYLON.Observable();
  65334. /**
  65335. * An event triggered when the postprocess changes its size.
  65336. */
  65337. this.onSizeChangedObservable = new BABYLON.Observable();
  65338. /**
  65339. * An event triggered when the postprocess applies its effect.
  65340. */
  65341. this.onApplyObservable = new BABYLON.Observable();
  65342. /**
  65343. * An event triggered before rendering the postprocess
  65344. */
  65345. this.onBeforeRenderObservable = new BABYLON.Observable();
  65346. /**
  65347. * An event triggered after rendering the postprocess
  65348. */
  65349. this.onAfterRenderObservable = new BABYLON.Observable();
  65350. if (camera != null) {
  65351. this._camera = camera;
  65352. this._scene = camera.getScene();
  65353. camera.attachPostProcess(this);
  65354. this._engine = this._scene.getEngine();
  65355. this._scene.postProcesses.push(this);
  65356. }
  65357. else if (engine) {
  65358. this._engine = engine;
  65359. this._engine.postProcesses.push(this);
  65360. }
  65361. this._options = options;
  65362. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65363. this._reusable = reusable || false;
  65364. this._textureType = textureType;
  65365. this._samplers = samplers || [];
  65366. this._samplers.push("textureSampler");
  65367. this._fragmentUrl = fragmentUrl;
  65368. this._vertexUrl = vertexUrl;
  65369. this._parameters = parameters || [];
  65370. this._parameters.push("scale");
  65371. this._indexParameters = indexParameters;
  65372. if (!blockCompilation) {
  65373. this.updateEffect(defines);
  65374. }
  65375. }
  65376. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65377. /**
  65378. * A function that is added to the onActivateObservable
  65379. */
  65380. set: function (callback) {
  65381. if (this._onActivateObserver) {
  65382. this.onActivateObservable.remove(this._onActivateObserver);
  65383. }
  65384. if (callback) {
  65385. this._onActivateObserver = this.onActivateObservable.add(callback);
  65386. }
  65387. },
  65388. enumerable: true,
  65389. configurable: true
  65390. });
  65391. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65392. /**
  65393. * A function that is added to the onSizeChangedObservable
  65394. */
  65395. set: function (callback) {
  65396. if (this._onSizeChangedObserver) {
  65397. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65398. }
  65399. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65400. },
  65401. enumerable: true,
  65402. configurable: true
  65403. });
  65404. Object.defineProperty(PostProcess.prototype, "onApply", {
  65405. /**
  65406. * A function that is added to the onApplyObservable
  65407. */
  65408. set: function (callback) {
  65409. if (this._onApplyObserver) {
  65410. this.onApplyObservable.remove(this._onApplyObserver);
  65411. }
  65412. this._onApplyObserver = this.onApplyObservable.add(callback);
  65413. },
  65414. enumerable: true,
  65415. configurable: true
  65416. });
  65417. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65418. /**
  65419. * A function that is added to the onBeforeRenderObservable
  65420. */
  65421. set: function (callback) {
  65422. if (this._onBeforeRenderObserver) {
  65423. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65424. }
  65425. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65426. },
  65427. enumerable: true,
  65428. configurable: true
  65429. });
  65430. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65431. /**
  65432. * A function that is added to the onAfterRenderObservable
  65433. */
  65434. set: function (callback) {
  65435. if (this._onAfterRenderObserver) {
  65436. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65437. }
  65438. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65439. },
  65440. enumerable: true,
  65441. configurable: true
  65442. });
  65443. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65444. /**
  65445. * 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
  65446. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65447. */
  65448. get: function () {
  65449. return this._textures.data[this._currentRenderTextureInd];
  65450. },
  65451. set: function (value) {
  65452. this._forcedOutputTexture = value;
  65453. },
  65454. enumerable: true,
  65455. configurable: true
  65456. });
  65457. /**
  65458. * Gets the camera which post process is applied to.
  65459. * @returns The camera the post process is applied to.
  65460. */
  65461. PostProcess.prototype.getCamera = function () {
  65462. return this._camera;
  65463. };
  65464. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65465. /**
  65466. * Gets the texel size of the postprocess.
  65467. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65468. */
  65469. get: function () {
  65470. if (this._shareOutputWithPostProcess) {
  65471. return this._shareOutputWithPostProcess.texelSize;
  65472. }
  65473. if (this._forcedOutputTexture) {
  65474. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65475. }
  65476. return this._texelSize;
  65477. },
  65478. enumerable: true,
  65479. configurable: true
  65480. });
  65481. /**
  65482. * Gets the engine which this post process belongs to.
  65483. * @returns The engine the post process was enabled with.
  65484. */
  65485. PostProcess.prototype.getEngine = function () {
  65486. return this._engine;
  65487. };
  65488. /**
  65489. * The effect that is created when initializing the post process.
  65490. * @returns The created effect corrisponding the the postprocess.
  65491. */
  65492. PostProcess.prototype.getEffect = function () {
  65493. return this._effect;
  65494. };
  65495. /**
  65496. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65497. * @param postProcess The post process to share the output with.
  65498. * @returns This post process.
  65499. */
  65500. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65501. this._disposeTextures();
  65502. this._shareOutputWithPostProcess = postProcess;
  65503. return this;
  65504. };
  65505. /**
  65506. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65507. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65508. */
  65509. PostProcess.prototype.useOwnOutput = function () {
  65510. if (this._textures.length == 0) {
  65511. this._textures = new BABYLON.SmartArray(2);
  65512. }
  65513. this._shareOutputWithPostProcess = null;
  65514. };
  65515. /**
  65516. * Updates the effect with the current post process compile time values and recompiles the shader.
  65517. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65518. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65519. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65520. * @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
  65521. * @param onCompiled Called when the shader has been compiled.
  65522. * @param onError Called if there is an error when compiling a shader.
  65523. */
  65524. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65525. if (defines === void 0) { defines = null; }
  65526. if (uniforms === void 0) { uniforms = null; }
  65527. if (samplers === void 0) { samplers = null; }
  65528. 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);
  65529. };
  65530. /**
  65531. * The post process is reusable if it can be used multiple times within one frame.
  65532. * @returns If the post process is reusable
  65533. */
  65534. PostProcess.prototype.isReusable = function () {
  65535. return this._reusable;
  65536. };
  65537. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65538. PostProcess.prototype.markTextureDirty = function () {
  65539. this.width = -1;
  65540. };
  65541. /**
  65542. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65543. * 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.
  65544. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65545. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65546. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65547. * @returns The target texture that was bound to be written to.
  65548. */
  65549. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65550. var _this = this;
  65551. if (sourceTexture === void 0) { sourceTexture = null; }
  65552. camera = camera || this._camera;
  65553. var scene = camera.getScene();
  65554. var engine = scene.getEngine();
  65555. var maxSize = engine.getCaps().maxTextureSize;
  65556. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65557. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65558. // 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
  65559. var webVRCamera = camera.parent;
  65560. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65561. requiredWidth /= 2;
  65562. }
  65563. var desiredWidth = (this._options.width || requiredWidth);
  65564. var desiredHeight = this._options.height || requiredHeight;
  65565. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65566. if (this.adaptScaleToCurrentViewport) {
  65567. var currentViewport = engine.currentViewport;
  65568. if (currentViewport) {
  65569. desiredWidth *= currentViewport.width;
  65570. desiredHeight *= currentViewport.height;
  65571. }
  65572. }
  65573. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65574. if (!this._options.width) {
  65575. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65576. }
  65577. if (!this._options.height) {
  65578. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65579. }
  65580. }
  65581. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65582. if (this._textures.length > 0) {
  65583. for (var i = 0; i < this._textures.length; i++) {
  65584. this._engine._releaseTexture(this._textures.data[i]);
  65585. }
  65586. this._textures.reset();
  65587. }
  65588. this.width = desiredWidth;
  65589. this.height = desiredHeight;
  65590. var textureSize = { width: this.width, height: this.height };
  65591. var textureOptions = {
  65592. generateMipMaps: false,
  65593. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65594. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65595. samplingMode: this.renderTargetSamplingMode,
  65596. type: this._textureType
  65597. };
  65598. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65599. if (this._reusable) {
  65600. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65601. }
  65602. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65603. this.onSizeChangedObservable.notifyObservers(this);
  65604. }
  65605. this._textures.forEach(function (texture) {
  65606. if (texture.samples !== _this.samples) {
  65607. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65608. }
  65609. });
  65610. }
  65611. var target;
  65612. if (this._shareOutputWithPostProcess) {
  65613. target = this._shareOutputWithPostProcess.inputTexture;
  65614. }
  65615. else if (this._forcedOutputTexture) {
  65616. target = this._forcedOutputTexture;
  65617. this.width = this._forcedOutputTexture.width;
  65618. this.height = this._forcedOutputTexture.height;
  65619. }
  65620. else {
  65621. target = this.inputTexture;
  65622. }
  65623. // Bind the input of this post process to be used as the output of the previous post process.
  65624. if (this.enablePixelPerfectMode) {
  65625. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65626. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65627. }
  65628. else {
  65629. this._scaleRatio.copyFromFloats(1, 1);
  65630. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65631. }
  65632. this.onActivateObservable.notifyObservers(camera);
  65633. // Clear
  65634. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65635. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65636. }
  65637. if (this._reusable) {
  65638. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65639. }
  65640. return target;
  65641. };
  65642. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65643. /**
  65644. * If the post process is supported.
  65645. */
  65646. get: function () {
  65647. return this._effect.isSupported;
  65648. },
  65649. enumerable: true,
  65650. configurable: true
  65651. });
  65652. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65653. /**
  65654. * The aspect ratio of the output texture.
  65655. */
  65656. get: function () {
  65657. if (this._shareOutputWithPostProcess) {
  65658. return this._shareOutputWithPostProcess.aspectRatio;
  65659. }
  65660. if (this._forcedOutputTexture) {
  65661. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65662. }
  65663. return this.width / this.height;
  65664. },
  65665. enumerable: true,
  65666. configurable: true
  65667. });
  65668. /**
  65669. * Get a value indicating if the post-process is ready to be used
  65670. * @returns true if the post-process is ready (shader is compiled)
  65671. */
  65672. PostProcess.prototype.isReady = function () {
  65673. return this._effect && this._effect.isReady();
  65674. };
  65675. /**
  65676. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65677. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65678. */
  65679. PostProcess.prototype.apply = function () {
  65680. // Check
  65681. if (!this._effect || !this._effect.isReady())
  65682. return null;
  65683. // States
  65684. this._engine.enableEffect(this._effect);
  65685. this._engine.setState(false);
  65686. this._engine.setDepthBuffer(false);
  65687. this._engine.setDepthWrite(false);
  65688. // Alpha
  65689. this._engine.setAlphaMode(this.alphaMode);
  65690. if (this.alphaConstants) {
  65691. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65692. }
  65693. // Bind the output texture of the preivous post process as the input to this post process.
  65694. var source;
  65695. if (this._shareOutputWithPostProcess) {
  65696. source = this._shareOutputWithPostProcess.inputTexture;
  65697. }
  65698. else if (this._forcedOutputTexture) {
  65699. source = this._forcedOutputTexture;
  65700. }
  65701. else {
  65702. source = this.inputTexture;
  65703. }
  65704. this._effect._bindTexture("textureSampler", source);
  65705. // Parameters
  65706. this._effect.setVector2("scale", this._scaleRatio);
  65707. this.onApplyObservable.notifyObservers(this._effect);
  65708. return this._effect;
  65709. };
  65710. PostProcess.prototype._disposeTextures = function () {
  65711. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65712. return;
  65713. }
  65714. if (this._textures.length > 0) {
  65715. for (var i = 0; i < this._textures.length; i++) {
  65716. this._engine._releaseTexture(this._textures.data[i]);
  65717. }
  65718. }
  65719. this._textures.dispose();
  65720. };
  65721. /**
  65722. * Disposes the post process.
  65723. * @param camera The camera to dispose the post process on.
  65724. */
  65725. PostProcess.prototype.dispose = function (camera) {
  65726. camera = camera || this._camera;
  65727. this._disposeTextures();
  65728. if (this._scene) {
  65729. var index_1 = this._scene.postProcesses.indexOf(this);
  65730. if (index_1 !== -1) {
  65731. this._scene.postProcesses.splice(index_1, 1);
  65732. }
  65733. }
  65734. else {
  65735. var index_2 = this._engine.postProcesses.indexOf(this);
  65736. if (index_2 !== -1) {
  65737. this._engine.postProcesses.splice(index_2, 1);
  65738. }
  65739. }
  65740. if (!camera) {
  65741. return;
  65742. }
  65743. camera.detachPostProcess(this);
  65744. var index = camera._postProcesses.indexOf(this);
  65745. if (index === 0 && camera._postProcesses.length > 0) {
  65746. var firstPostProcess = this._camera._getFirstPostProcess();
  65747. if (firstPostProcess) {
  65748. firstPostProcess.markTextureDirty();
  65749. }
  65750. }
  65751. this.onActivateObservable.clear();
  65752. this.onAfterRenderObservable.clear();
  65753. this.onApplyObservable.clear();
  65754. this.onBeforeRenderObservable.clear();
  65755. this.onSizeChangedObservable.clear();
  65756. };
  65757. return PostProcess;
  65758. }());
  65759. BABYLON.PostProcess = PostProcess;
  65760. })(BABYLON || (BABYLON = {}));
  65761. //# sourceMappingURL=babylon.postProcess.js.map
  65762. var BABYLON;
  65763. (function (BABYLON) {
  65764. var PassPostProcess = /** @class */ (function (_super) {
  65765. __extends(PassPostProcess, _super);
  65766. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65767. if (camera === void 0) { camera = null; }
  65768. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65769. if (blockCompilation === void 0) { blockCompilation = false; }
  65770. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65771. }
  65772. return PassPostProcess;
  65773. }(BABYLON.PostProcess));
  65774. BABYLON.PassPostProcess = PassPostProcess;
  65775. })(BABYLON || (BABYLON = {}));
  65776. //# sourceMappingURL=babylon.passPostProcess.js.map
  65777. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65778. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65779. s = arguments[i];
  65780. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65781. t[p] = s[p];
  65782. }
  65783. return t;
  65784. };
  65785. var BABYLON;
  65786. (function (BABYLON) {
  65787. /**
  65788. * Default implementation IShadowGenerator.
  65789. * This is the main object responsible of generating shadows in the framework.
  65790. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65791. */
  65792. var ShadowGenerator = /** @class */ (function () {
  65793. /**
  65794. * Creates a ShadowGenerator object.
  65795. * A ShadowGenerator is the required tool to use the shadows.
  65796. * Each light casting shadows needs to use its own ShadowGenerator.
  65797. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65798. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65799. * @param light The light object generating the shadows.
  65800. * @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.
  65801. */
  65802. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65803. this._bias = 0.00005;
  65804. this._normalBias = 0;
  65805. this._blurBoxOffset = 1;
  65806. this._blurScale = 2;
  65807. this._blurKernel = 1;
  65808. this._useKernelBlur = false;
  65809. this._filter = ShadowGenerator.FILTER_NONE;
  65810. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65811. this._contactHardeningLightSizeUVRatio = 0.1;
  65812. this._darkness = 0;
  65813. this._transparencyShadow = false;
  65814. /**
  65815. * Controls the extent to which the shadows fade out at the edge of the frustum
  65816. * Used only by directionals and spots
  65817. */
  65818. this.frustumEdgeFalloff = 0;
  65819. /**
  65820. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65821. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65822. * It might on the other hand introduce peter panning.
  65823. */
  65824. this.forceBackFacesOnly = false;
  65825. this._lightDirection = BABYLON.Vector3.Zero();
  65826. this._viewMatrix = BABYLON.Matrix.Zero();
  65827. this._projectionMatrix = BABYLON.Matrix.Zero();
  65828. this._transformMatrix = BABYLON.Matrix.Zero();
  65829. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65830. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65831. this._currentFaceIndex = 0;
  65832. this._currentFaceIndexCache = 0;
  65833. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65834. this._mapSize = mapSize;
  65835. this._light = light;
  65836. this._scene = light.getScene();
  65837. light._shadowGenerator = this;
  65838. // Texture type fallback from float to int if not supported.
  65839. var caps = this._scene.getEngine().getCaps();
  65840. if (!useFullFloatFirst) {
  65841. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65842. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65843. }
  65844. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65845. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65846. }
  65847. else {
  65848. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65849. }
  65850. }
  65851. else {
  65852. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65853. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65854. }
  65855. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65856. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65857. }
  65858. else {
  65859. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65860. }
  65861. }
  65862. this._initializeGenerator();
  65863. this._applyFilterValues();
  65864. }
  65865. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65866. /**
  65867. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65868. */
  65869. get: function () {
  65870. return this._bias;
  65871. },
  65872. /**
  65873. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65874. */
  65875. set: function (bias) {
  65876. this._bias = bias;
  65877. },
  65878. enumerable: true,
  65879. configurable: true
  65880. });
  65881. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65882. /**
  65883. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65884. */
  65885. get: function () {
  65886. return this._normalBias;
  65887. },
  65888. /**
  65889. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65890. */
  65891. set: function (normalBias) {
  65892. this._normalBias = normalBias;
  65893. },
  65894. enumerable: true,
  65895. configurable: true
  65896. });
  65897. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65898. /**
  65899. * Gets the blur box offset: offset applied during the blur pass.
  65900. * Only usefull if useKernelBlur = false
  65901. */
  65902. get: function () {
  65903. return this._blurBoxOffset;
  65904. },
  65905. /**
  65906. * Sets the blur box offset: offset applied during the blur pass.
  65907. * Only usefull if useKernelBlur = false
  65908. */
  65909. set: function (value) {
  65910. if (this._blurBoxOffset === value) {
  65911. return;
  65912. }
  65913. this._blurBoxOffset = value;
  65914. this._disposeBlurPostProcesses();
  65915. },
  65916. enumerable: true,
  65917. configurable: true
  65918. });
  65919. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65920. /**
  65921. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65922. * 2 means half of the size.
  65923. */
  65924. get: function () {
  65925. return this._blurScale;
  65926. },
  65927. /**
  65928. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65929. * 2 means half of the size.
  65930. */
  65931. set: function (value) {
  65932. if (this._blurScale === value) {
  65933. return;
  65934. }
  65935. this._blurScale = value;
  65936. this._disposeBlurPostProcesses();
  65937. },
  65938. enumerable: true,
  65939. configurable: true
  65940. });
  65941. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65942. /**
  65943. * Gets the blur kernel: kernel size of the blur pass.
  65944. * Only usefull if useKernelBlur = true
  65945. */
  65946. get: function () {
  65947. return this._blurKernel;
  65948. },
  65949. /**
  65950. * Sets the blur kernel: kernel size of the blur pass.
  65951. * Only usefull if useKernelBlur = true
  65952. */
  65953. set: function (value) {
  65954. if (this._blurKernel === value) {
  65955. return;
  65956. }
  65957. this._blurKernel = value;
  65958. this._disposeBlurPostProcesses();
  65959. },
  65960. enumerable: true,
  65961. configurable: true
  65962. });
  65963. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65964. /**
  65965. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65966. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65967. */
  65968. get: function () {
  65969. return this._useKernelBlur;
  65970. },
  65971. /**
  65972. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65973. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65974. */
  65975. set: function (value) {
  65976. if (this._useKernelBlur === value) {
  65977. return;
  65978. }
  65979. this._useKernelBlur = value;
  65980. this._disposeBlurPostProcesses();
  65981. },
  65982. enumerable: true,
  65983. configurable: true
  65984. });
  65985. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65986. /**
  65987. * Gets the depth scale used in ESM mode.
  65988. */
  65989. get: function () {
  65990. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65991. },
  65992. /**
  65993. * Sets the depth scale used in ESM mode.
  65994. * This can override the scale stored on the light.
  65995. */
  65996. set: function (value) {
  65997. this._depthScale = value;
  65998. },
  65999. enumerable: true,
  66000. configurable: true
  66001. });
  66002. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66003. /**
  66004. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66005. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66006. */
  66007. get: function () {
  66008. return this._filter;
  66009. },
  66010. /**
  66011. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66012. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66013. */
  66014. set: function (value) {
  66015. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66016. if (this._light.needCube()) {
  66017. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66018. this.useExponentialShadowMap = true;
  66019. return;
  66020. }
  66021. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66022. this.useCloseExponentialShadowMap = true;
  66023. return;
  66024. }
  66025. // PCF on cubemap would also be expensive
  66026. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66027. this.usePoissonSampling = true;
  66028. return;
  66029. }
  66030. }
  66031. // Weblg1 fallback for PCF.
  66032. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66033. if (this._scene.getEngine().webGLVersion === 1) {
  66034. this.usePoissonSampling = true;
  66035. return;
  66036. }
  66037. }
  66038. if (this._filter === value) {
  66039. return;
  66040. }
  66041. this._filter = value;
  66042. this._disposeBlurPostProcesses();
  66043. this._applyFilterValues();
  66044. this._light._markMeshesAsLightDirty();
  66045. },
  66046. enumerable: true,
  66047. configurable: true
  66048. });
  66049. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66050. /**
  66051. * Gets if the current filter is set to Poisson Sampling.
  66052. */
  66053. get: function () {
  66054. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66055. },
  66056. /**
  66057. * Sets the current filter to Poisson Sampling.
  66058. */
  66059. set: function (value) {
  66060. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66061. return;
  66062. }
  66063. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66064. },
  66065. enumerable: true,
  66066. configurable: true
  66067. });
  66068. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66069. /**
  66070. * Gets if the current filter is set to VSM.
  66071. * DEPRECATED. Should use useExponentialShadowMap instead.
  66072. */
  66073. get: function () {
  66074. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66075. return this.useExponentialShadowMap;
  66076. },
  66077. /**
  66078. * Sets the current filter is to VSM.
  66079. * DEPRECATED. Should use useExponentialShadowMap instead.
  66080. */
  66081. set: function (value) {
  66082. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66083. this.useExponentialShadowMap = value;
  66084. },
  66085. enumerable: true,
  66086. configurable: true
  66087. });
  66088. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66089. /**
  66090. * Gets if the current filter is set to blurred VSM.
  66091. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66092. */
  66093. get: function () {
  66094. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66095. return this.useBlurExponentialShadowMap;
  66096. },
  66097. /**
  66098. * Sets the current filter is to blurred VSM.
  66099. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66100. */
  66101. set: function (value) {
  66102. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66103. this.useBlurExponentialShadowMap = value;
  66104. },
  66105. enumerable: true,
  66106. configurable: true
  66107. });
  66108. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66109. /**
  66110. * Gets if the current filter is set to ESM.
  66111. */
  66112. get: function () {
  66113. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66114. },
  66115. /**
  66116. * Sets the current filter is to ESM.
  66117. */
  66118. set: function (value) {
  66119. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66120. return;
  66121. }
  66122. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66123. },
  66124. enumerable: true,
  66125. configurable: true
  66126. });
  66127. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66128. /**
  66129. * Gets if the current filter is set to filtered ESM.
  66130. */
  66131. get: function () {
  66132. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66133. },
  66134. /**
  66135. * Gets if the current filter is set to filtered ESM.
  66136. */
  66137. set: function (value) {
  66138. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66139. return;
  66140. }
  66141. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66142. },
  66143. enumerable: true,
  66144. configurable: true
  66145. });
  66146. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66147. /**
  66148. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66149. * exponential to prevent steep falloff artifacts).
  66150. */
  66151. get: function () {
  66152. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66153. },
  66154. /**
  66155. * Sets the current filter to "close ESM" (using the inverse of the
  66156. * exponential to prevent steep falloff artifacts).
  66157. */
  66158. set: function (value) {
  66159. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66160. return;
  66161. }
  66162. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66163. },
  66164. enumerable: true,
  66165. configurable: true
  66166. });
  66167. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66168. /**
  66169. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66170. * exponential to prevent steep falloff artifacts).
  66171. */
  66172. get: function () {
  66173. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66174. },
  66175. /**
  66176. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66177. * exponential to prevent steep falloff artifacts).
  66178. */
  66179. set: function (value) {
  66180. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66181. return;
  66182. }
  66183. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66184. },
  66185. enumerable: true,
  66186. configurable: true
  66187. });
  66188. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66189. /**
  66190. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66191. */
  66192. get: function () {
  66193. return this.filter === ShadowGenerator.FILTER_PCF;
  66194. },
  66195. /**
  66196. * Sets the current filter to "PCF" (percentage closer filtering).
  66197. */
  66198. set: function (value) {
  66199. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66200. return;
  66201. }
  66202. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66203. },
  66204. enumerable: true,
  66205. configurable: true
  66206. });
  66207. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66208. /**
  66209. * Gets the PCF or PCSS Quality.
  66210. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66211. */
  66212. get: function () {
  66213. return this._filteringQuality;
  66214. },
  66215. /**
  66216. * Sets the PCF or PCSS Quality.
  66217. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66218. */
  66219. set: function (filteringQuality) {
  66220. this._filteringQuality = filteringQuality;
  66221. },
  66222. enumerable: true,
  66223. configurable: true
  66224. });
  66225. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66226. /**
  66227. * Gets if the current filter is set to "PCSS" (contact hardening).
  66228. */
  66229. get: function () {
  66230. return this.filter === ShadowGenerator.FILTER_PCSS;
  66231. },
  66232. /**
  66233. * Sets the current filter to "PCSS" (contact hardening).
  66234. */
  66235. set: function (value) {
  66236. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66237. return;
  66238. }
  66239. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66240. },
  66241. enumerable: true,
  66242. configurable: true
  66243. });
  66244. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66245. /**
  66246. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66247. * Using a ratio helps keeping shape stability independently of the map size.
  66248. *
  66249. * It does not account for the light projection as it was having too much
  66250. * instability during the light setup or during light position changes.
  66251. *
  66252. * Only valid if useContactHardeningShadow is true.
  66253. */
  66254. get: function () {
  66255. return this._contactHardeningLightSizeUVRatio;
  66256. },
  66257. /**
  66258. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66259. * Using a ratio helps keeping shape stability independently of the map size.
  66260. *
  66261. * It does not account for the light projection as it was having too much
  66262. * instability during the light setup or during light position changes.
  66263. *
  66264. * Only valid if useContactHardeningShadow is true.
  66265. */
  66266. set: function (contactHardeningLightSizeUVRatio) {
  66267. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66268. },
  66269. enumerable: true,
  66270. configurable: true
  66271. });
  66272. /**
  66273. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66274. * 0 means strongest and 1 would means no shadow.
  66275. * @returns the darkness.
  66276. */
  66277. ShadowGenerator.prototype.getDarkness = function () {
  66278. return this._darkness;
  66279. };
  66280. /**
  66281. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66282. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66283. * @returns the shadow generator allowing fluent coding.
  66284. */
  66285. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66286. if (darkness >= 1.0)
  66287. this._darkness = 1.0;
  66288. else if (darkness <= 0.0)
  66289. this._darkness = 0.0;
  66290. else
  66291. this._darkness = darkness;
  66292. return this;
  66293. };
  66294. /**
  66295. * Sets the ability to have transparent shadow (boolean).
  66296. * @param transparent True if transparent else False
  66297. * @returns the shadow generator allowing fluent coding
  66298. */
  66299. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66300. this._transparencyShadow = transparent;
  66301. return this;
  66302. };
  66303. /**
  66304. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66305. * @returns The render target texture if present otherwise, null
  66306. */
  66307. ShadowGenerator.prototype.getShadowMap = function () {
  66308. return this._shadowMap;
  66309. };
  66310. /**
  66311. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66312. * @returns The render target texture if the shadow map is present otherwise, null
  66313. */
  66314. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66315. if (this._shadowMap2) {
  66316. return this._shadowMap2;
  66317. }
  66318. return this._shadowMap;
  66319. };
  66320. /**
  66321. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66322. * @param mesh Mesh to add
  66323. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66324. * @returns the Shadow Generator itself
  66325. */
  66326. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66327. if (includeDescendants === void 0) { includeDescendants = true; }
  66328. if (!this._shadowMap) {
  66329. return this;
  66330. }
  66331. if (!this._shadowMap.renderList) {
  66332. this._shadowMap.renderList = [];
  66333. }
  66334. this._shadowMap.renderList.push(mesh);
  66335. if (includeDescendants) {
  66336. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66337. }
  66338. return this;
  66339. var _a;
  66340. };
  66341. /**
  66342. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66343. * @param mesh Mesh to remove
  66344. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66345. * @returns the Shadow Generator itself
  66346. */
  66347. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66348. if (includeDescendants === void 0) { includeDescendants = true; }
  66349. if (!this._shadowMap || !this._shadowMap.renderList) {
  66350. return this;
  66351. }
  66352. var index = this._shadowMap.renderList.indexOf(mesh);
  66353. if (index !== -1) {
  66354. this._shadowMap.renderList.splice(index, 1);
  66355. }
  66356. if (includeDescendants) {
  66357. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66358. var child = _a[_i];
  66359. this.removeShadowCaster(child);
  66360. }
  66361. }
  66362. return this;
  66363. };
  66364. /**
  66365. * Returns the associated light object.
  66366. * @returns the light generating the shadow
  66367. */
  66368. ShadowGenerator.prototype.getLight = function () {
  66369. return this._light;
  66370. };
  66371. ShadowGenerator.prototype._initializeGenerator = function () {
  66372. this._light._markMeshesAsLightDirty();
  66373. this._initializeShadowMap();
  66374. };
  66375. ShadowGenerator.prototype._initializeShadowMap = function () {
  66376. var _this = this;
  66377. // Render target
  66378. var engine = this._scene.getEngine();
  66379. if (engine.webGLVersion > 1) {
  66380. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66381. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66382. }
  66383. else {
  66384. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66385. }
  66386. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66387. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66388. this._shadowMap.anisotropicFilteringLevel = 1;
  66389. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66390. this._shadowMap.renderParticles = false;
  66391. this._shadowMap.ignoreCameraViewport = true;
  66392. // Record Face Index before render.
  66393. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66394. _this._currentFaceIndex = faceIndex;
  66395. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66396. engine.setColorWrite(false);
  66397. }
  66398. });
  66399. // Custom render function.
  66400. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66401. // Blur if required afer render.
  66402. this._shadowMap.onAfterUnbindObservable.add(function () {
  66403. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66404. engine.setColorWrite(true);
  66405. }
  66406. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66407. return;
  66408. }
  66409. var shadowMap = _this.getShadowMapForRendering();
  66410. if (shadowMap) {
  66411. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66412. }
  66413. });
  66414. // Clear according to the chosen filter.
  66415. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66416. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66417. this._shadowMap.onClearObservable.add(function (engine) {
  66418. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66419. engine.clear(clearOne, false, true, false);
  66420. }
  66421. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66422. engine.clear(clearZero, true, true, false);
  66423. }
  66424. else {
  66425. engine.clear(clearOne, true, true, false);
  66426. }
  66427. });
  66428. };
  66429. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66430. var _this = this;
  66431. var engine = this._scene.getEngine();
  66432. var targetSize = this._mapSize / this.blurScale;
  66433. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66434. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66435. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66436. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66437. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66438. }
  66439. if (this.useKernelBlur) {
  66440. 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);
  66441. this._kernelBlurXPostprocess.width = targetSize;
  66442. this._kernelBlurXPostprocess.height = targetSize;
  66443. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66444. effect.setTexture("textureSampler", _this._shadowMap);
  66445. });
  66446. 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);
  66447. this._kernelBlurXPostprocess.autoClear = false;
  66448. this._kernelBlurYPostprocess.autoClear = false;
  66449. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66450. this._kernelBlurXPostprocess.packedFloat = true;
  66451. this._kernelBlurYPostprocess.packedFloat = true;
  66452. }
  66453. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66454. }
  66455. else {
  66456. 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);
  66457. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66458. effect.setFloat2("screenSize", targetSize, targetSize);
  66459. effect.setTexture("textureSampler", _this._shadowMap);
  66460. });
  66461. this._boxBlurPostprocess.autoClear = false;
  66462. this._blurPostProcesses = [this._boxBlurPostprocess];
  66463. }
  66464. };
  66465. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66466. var index;
  66467. var engine = this._scene.getEngine();
  66468. if (depthOnlySubMeshes.length) {
  66469. engine.setColorWrite(false);
  66470. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66471. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66472. }
  66473. engine.setColorWrite(true);
  66474. }
  66475. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66476. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66477. }
  66478. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66479. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66480. }
  66481. if (this._transparencyShadow) {
  66482. for (index = 0; index < transparentSubMeshes.length; index++) {
  66483. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66484. }
  66485. }
  66486. };
  66487. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66488. var _this = this;
  66489. var mesh = subMesh.getRenderingMesh();
  66490. var scene = this._scene;
  66491. var engine = scene.getEngine();
  66492. var material = subMesh.getMaterial();
  66493. if (!material) {
  66494. return;
  66495. }
  66496. // Culling
  66497. engine.setState(material.backFaceCulling);
  66498. // Managing instances
  66499. var batch = mesh._getInstancesRenderList(subMesh._id);
  66500. if (batch.mustReturn) {
  66501. return;
  66502. }
  66503. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66504. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66505. engine.enableEffect(this._effect);
  66506. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66507. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66508. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66509. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66510. this._effect.setVector3("lightData", this._cachedDirection);
  66511. }
  66512. else {
  66513. this._effect.setVector3("lightData", this._cachedPosition);
  66514. }
  66515. if (scene.activeCamera) {
  66516. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66517. }
  66518. // Alpha test
  66519. if (material && material.needAlphaTesting()) {
  66520. var alphaTexture = material.getAlphaTestTexture();
  66521. if (alphaTexture) {
  66522. this._effect.setTexture("diffuseSampler", alphaTexture);
  66523. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66524. }
  66525. }
  66526. // Bones
  66527. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66528. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66529. }
  66530. // Morph targets
  66531. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66532. if (this.forceBackFacesOnly) {
  66533. engine.setState(true, 0, false, true);
  66534. }
  66535. // Draw
  66536. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66537. if (this.forceBackFacesOnly) {
  66538. engine.setState(true, 0, false, false);
  66539. }
  66540. }
  66541. else {
  66542. // Need to reset refresh rate of the shadowMap
  66543. if (this._shadowMap) {
  66544. this._shadowMap.resetRefreshCounter();
  66545. }
  66546. }
  66547. };
  66548. ShadowGenerator.prototype._applyFilterValues = function () {
  66549. if (!this._shadowMap) {
  66550. return;
  66551. }
  66552. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66553. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66554. }
  66555. else {
  66556. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66557. }
  66558. };
  66559. /**
  66560. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66561. * @param onCompiled Callback triggered at the and of the effects compilation
  66562. * @param options Sets of optional options forcing the compilation with different modes
  66563. */
  66564. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66565. var _this = this;
  66566. var localOptions = __assign({ useInstances: false }, options);
  66567. var shadowMap = this.getShadowMap();
  66568. if (!shadowMap) {
  66569. if (onCompiled) {
  66570. onCompiled(this);
  66571. }
  66572. return;
  66573. }
  66574. var renderList = shadowMap.renderList;
  66575. if (!renderList) {
  66576. if (onCompiled) {
  66577. onCompiled(this);
  66578. }
  66579. return;
  66580. }
  66581. var subMeshes = new Array();
  66582. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66583. var mesh = renderList_1[_i];
  66584. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66585. }
  66586. if (subMeshes.length === 0) {
  66587. if (onCompiled) {
  66588. onCompiled(this);
  66589. }
  66590. return;
  66591. }
  66592. var currentIndex = 0;
  66593. var checkReady = function () {
  66594. if (!_this._scene || !_this._scene.getEngine()) {
  66595. return;
  66596. }
  66597. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66598. currentIndex++;
  66599. if (currentIndex >= subMeshes.length) {
  66600. if (onCompiled) {
  66601. onCompiled(_this);
  66602. }
  66603. return;
  66604. }
  66605. }
  66606. setTimeout(checkReady, 16);
  66607. };
  66608. checkReady();
  66609. };
  66610. /**
  66611. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66612. * @param options Sets of optional options forcing the compilation with different modes
  66613. * @returns A promise that resolves when the compilation completes
  66614. */
  66615. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66616. var _this = this;
  66617. return new Promise(function (resolve) {
  66618. _this.forceCompilation(function () {
  66619. resolve();
  66620. }, options);
  66621. });
  66622. };
  66623. /**
  66624. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66625. * @param subMesh The submesh we want to render in the shadow map
  66626. * @param useInstances Defines wether will draw in the map using instances
  66627. * @returns true if ready otherwise, false
  66628. */
  66629. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66630. var defines = [];
  66631. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66632. defines.push("#define FLOAT");
  66633. }
  66634. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66635. defines.push("#define ESM");
  66636. }
  66637. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66638. defines.push("#define DEPTHTEXTURE");
  66639. }
  66640. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66641. var mesh = subMesh.getMesh();
  66642. var material = subMesh.getMaterial();
  66643. // Normal bias.
  66644. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66645. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66646. defines.push("#define NORMAL");
  66647. if (mesh.nonUniformScaling) {
  66648. defines.push("#define NONUNIFORMSCALING");
  66649. }
  66650. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66651. defines.push("#define DIRECTIONINLIGHTDATA");
  66652. }
  66653. }
  66654. // Alpha test
  66655. if (material && material.needAlphaTesting()) {
  66656. var alphaTexture = material.getAlphaTestTexture();
  66657. if (alphaTexture) {
  66658. defines.push("#define ALPHATEST");
  66659. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66660. attribs.push(BABYLON.VertexBuffer.UVKind);
  66661. defines.push("#define UV1");
  66662. }
  66663. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66664. if (alphaTexture.coordinatesIndex === 1) {
  66665. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66666. defines.push("#define UV2");
  66667. }
  66668. }
  66669. }
  66670. }
  66671. // Bones
  66672. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66673. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66674. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66675. if (mesh.numBoneInfluencers > 4) {
  66676. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66677. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66678. }
  66679. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66680. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66681. }
  66682. else {
  66683. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66684. }
  66685. // Morph targets
  66686. var manager = mesh.morphTargetManager;
  66687. var morphInfluencers = 0;
  66688. if (manager) {
  66689. if (manager.numInfluencers > 0) {
  66690. defines.push("#define MORPHTARGETS");
  66691. morphInfluencers = manager.numInfluencers;
  66692. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66693. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66694. }
  66695. }
  66696. // Instances
  66697. if (useInstances) {
  66698. defines.push("#define INSTANCES");
  66699. attribs.push("world0");
  66700. attribs.push("world1");
  66701. attribs.push("world2");
  66702. attribs.push("world3");
  66703. }
  66704. // Get correct effect
  66705. var join = defines.join("\n");
  66706. if (this._cachedDefines !== join) {
  66707. this._cachedDefines = join;
  66708. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66709. }
  66710. if (!this._effect.isReady()) {
  66711. return false;
  66712. }
  66713. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66714. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66715. this._initializeBlurRTTAndPostProcesses();
  66716. }
  66717. }
  66718. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66719. return false;
  66720. }
  66721. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66722. return false;
  66723. }
  66724. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66725. return false;
  66726. }
  66727. return true;
  66728. };
  66729. /**
  66730. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66731. * @param defines Defines of the material we want to update
  66732. * @param lightIndex Index of the light in the enabled light list of the material
  66733. */
  66734. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66735. var scene = this._scene;
  66736. var light = this._light;
  66737. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66738. return;
  66739. }
  66740. defines["SHADOW" + lightIndex] = true;
  66741. if (this.useContactHardeningShadow) {
  66742. defines["SHADOWPCSS" + lightIndex] = true;
  66743. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66744. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66745. }
  66746. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66747. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66748. }
  66749. // else default to high.
  66750. }
  66751. if (this.usePercentageCloserFiltering) {
  66752. defines["SHADOWPCF" + lightIndex] = true;
  66753. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66754. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66755. }
  66756. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66757. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66758. }
  66759. // else default to high.
  66760. }
  66761. else if (this.usePoissonSampling) {
  66762. defines["SHADOWPOISSON" + lightIndex] = true;
  66763. }
  66764. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66765. defines["SHADOWESM" + lightIndex] = true;
  66766. }
  66767. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66768. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66769. }
  66770. if (light.needCube()) {
  66771. defines["SHADOWCUBE" + lightIndex] = true;
  66772. }
  66773. };
  66774. /**
  66775. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66776. * defined in the generator but impacting the effect).
  66777. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66778. * @param effect The effect we are binfing the information for
  66779. */
  66780. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66781. var light = this._light;
  66782. var scene = this._scene;
  66783. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66784. return;
  66785. }
  66786. var camera = scene.activeCamera;
  66787. if (!camera) {
  66788. return;
  66789. }
  66790. var shadowMap = this.getShadowMap();
  66791. if (!shadowMap) {
  66792. return;
  66793. }
  66794. if (!light.needCube()) {
  66795. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66796. }
  66797. // Only PCF uses depth stencil texture.
  66798. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66799. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66800. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66801. }
  66802. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66803. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66804. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66805. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66806. }
  66807. else {
  66808. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66809. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66810. }
  66811. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66812. };
  66813. /**
  66814. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66815. * (eq to shadow prjection matrix * light transform matrix)
  66816. * @returns The transform matrix used to create the shadow map
  66817. */
  66818. ShadowGenerator.prototype.getTransformMatrix = function () {
  66819. var scene = this._scene;
  66820. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66821. return this._transformMatrix;
  66822. }
  66823. this._currentRenderID = scene.getRenderId();
  66824. this._currentFaceIndexCache = this._currentFaceIndex;
  66825. var lightPosition = this._light.position;
  66826. if (this._light.computeTransformedInformation()) {
  66827. lightPosition = this._light.transformedPosition;
  66828. }
  66829. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66830. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66831. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66832. }
  66833. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66834. this._cachedPosition.copyFrom(lightPosition);
  66835. this._cachedDirection.copyFrom(this._lightDirection);
  66836. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66837. var shadowMap = this.getShadowMap();
  66838. if (shadowMap) {
  66839. var renderList = shadowMap.renderList;
  66840. if (renderList) {
  66841. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66842. }
  66843. }
  66844. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66845. }
  66846. return this._transformMatrix;
  66847. };
  66848. /**
  66849. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66850. * Cube and 2D textures for instance.
  66851. */
  66852. ShadowGenerator.prototype.recreateShadowMap = function () {
  66853. var shadowMap = this._shadowMap;
  66854. if (!shadowMap) {
  66855. return;
  66856. }
  66857. // Track render list.
  66858. var renderList = shadowMap.renderList;
  66859. // Clean up existing data.
  66860. this._disposeRTTandPostProcesses();
  66861. // Reinitializes.
  66862. this._initializeGenerator();
  66863. // Reaffect the filter to ensure a correct fallback if necessary.
  66864. this.filter = this.filter;
  66865. // Reaffect the filter.
  66866. this._applyFilterValues();
  66867. // Reaffect Render List.
  66868. this._shadowMap.renderList = renderList;
  66869. };
  66870. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66871. if (this._shadowMap2) {
  66872. this._shadowMap2.dispose();
  66873. this._shadowMap2 = null;
  66874. }
  66875. if (this._boxBlurPostprocess) {
  66876. this._boxBlurPostprocess.dispose();
  66877. this._boxBlurPostprocess = null;
  66878. }
  66879. if (this._kernelBlurXPostprocess) {
  66880. this._kernelBlurXPostprocess.dispose();
  66881. this._kernelBlurXPostprocess = null;
  66882. }
  66883. if (this._kernelBlurYPostprocess) {
  66884. this._kernelBlurYPostprocess.dispose();
  66885. this._kernelBlurYPostprocess = null;
  66886. }
  66887. this._blurPostProcesses = [];
  66888. };
  66889. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66890. if (this._shadowMap) {
  66891. this._shadowMap.dispose();
  66892. this._shadowMap = null;
  66893. }
  66894. this._disposeBlurPostProcesses();
  66895. };
  66896. /**
  66897. * Disposes the ShadowGenerator.
  66898. * Returns nothing.
  66899. */
  66900. ShadowGenerator.prototype.dispose = function () {
  66901. this._disposeRTTandPostProcesses();
  66902. if (this._light) {
  66903. this._light._shadowGenerator = null;
  66904. this._light._markMeshesAsLightDirty();
  66905. }
  66906. };
  66907. /**
  66908. * Serializes the shadow generator setup to a json object.
  66909. * @returns The serialized JSON object
  66910. */
  66911. ShadowGenerator.prototype.serialize = function () {
  66912. var serializationObject = {};
  66913. var shadowMap = this.getShadowMap();
  66914. if (!shadowMap) {
  66915. return serializationObject;
  66916. }
  66917. serializationObject.lightId = this._light.id;
  66918. serializationObject.mapSize = shadowMap.getRenderSize();
  66919. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66920. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66921. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66922. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66923. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66924. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66925. serializationObject.depthScale = this.depthScale;
  66926. serializationObject.darkness = this.getDarkness();
  66927. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66928. serializationObject.blurKernel = this.blurKernel;
  66929. serializationObject.blurScale = this.blurScale;
  66930. serializationObject.useKernelBlur = this.useKernelBlur;
  66931. serializationObject.transparencyShadow = this._transparencyShadow;
  66932. serializationObject.bias = this.bias;
  66933. serializationObject.normalBias = this.normalBias;
  66934. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66935. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66936. serializationObject.filteringQuality = this.filteringQuality;
  66937. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66938. serializationObject.renderList = [];
  66939. if (shadowMap.renderList) {
  66940. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66941. var mesh = shadowMap.renderList[meshIndex];
  66942. serializationObject.renderList.push(mesh.id);
  66943. }
  66944. }
  66945. return serializationObject;
  66946. };
  66947. /**
  66948. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66949. * @param parsedShadowGenerator The JSON object to parse
  66950. * @param scene The scene to create the shadow map for
  66951. * @returns The parsed shadow generator
  66952. */
  66953. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66954. //casting to point light, as light is missing the position attr and typescript complains.
  66955. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66956. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66957. var shadowMap = shadowGenerator.getShadowMap();
  66958. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66959. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66960. meshes.forEach(function (mesh) {
  66961. if (!shadowMap) {
  66962. return;
  66963. }
  66964. if (!shadowMap.renderList) {
  66965. shadowMap.renderList = [];
  66966. }
  66967. shadowMap.renderList.push(mesh);
  66968. });
  66969. }
  66970. if (parsedShadowGenerator.usePoissonSampling) {
  66971. shadowGenerator.usePoissonSampling = true;
  66972. }
  66973. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66974. shadowGenerator.useExponentialShadowMap = true;
  66975. }
  66976. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66977. shadowGenerator.useBlurExponentialShadowMap = true;
  66978. }
  66979. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66980. shadowGenerator.useCloseExponentialShadowMap = true;
  66981. }
  66982. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66983. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66984. }
  66985. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66986. shadowGenerator.usePercentageCloserFiltering = true;
  66987. }
  66988. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66989. shadowGenerator.useContactHardeningShadow = true;
  66990. }
  66991. if (parsedShadowGenerator.filteringQuality) {
  66992. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66993. }
  66994. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66995. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66996. }
  66997. // Backward compat
  66998. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66999. shadowGenerator.useExponentialShadowMap = true;
  67000. }
  67001. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67002. shadowGenerator.useBlurExponentialShadowMap = true;
  67003. }
  67004. if (parsedShadowGenerator.depthScale) {
  67005. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67006. }
  67007. if (parsedShadowGenerator.blurScale) {
  67008. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67009. }
  67010. if (parsedShadowGenerator.blurBoxOffset) {
  67011. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67012. }
  67013. if (parsedShadowGenerator.useKernelBlur) {
  67014. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67015. }
  67016. if (parsedShadowGenerator.blurKernel) {
  67017. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67018. }
  67019. if (parsedShadowGenerator.bias !== undefined) {
  67020. shadowGenerator.bias = parsedShadowGenerator.bias;
  67021. }
  67022. if (parsedShadowGenerator.normalBias !== undefined) {
  67023. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67024. }
  67025. if (parsedShadowGenerator.darkness) {
  67026. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67027. }
  67028. if (parsedShadowGenerator.transparencyShadow) {
  67029. shadowGenerator.setTransparencyShadow(true);
  67030. }
  67031. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67032. return shadowGenerator;
  67033. };
  67034. /**
  67035. * Shadow generator mode None: no filtering applied.
  67036. */
  67037. ShadowGenerator.FILTER_NONE = 0;
  67038. /**
  67039. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67040. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67041. */
  67042. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67043. /**
  67044. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67045. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67046. */
  67047. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67048. /**
  67049. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67050. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67051. */
  67052. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67053. /**
  67054. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67055. * edge artifacts on steep falloff.
  67056. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67057. */
  67058. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67059. /**
  67060. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67061. * edge artifacts on steep falloff.
  67062. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67063. */
  67064. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67065. /**
  67066. * Shadow generator mode PCF: Percentage Closer Filtering
  67067. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67068. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67069. */
  67070. ShadowGenerator.FILTER_PCF = 6;
  67071. /**
  67072. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67073. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67074. * Contact Hardening
  67075. */
  67076. ShadowGenerator.FILTER_PCSS = 7;
  67077. /**
  67078. * Reserved for PCF and PCSS
  67079. * Highest Quality.
  67080. *
  67081. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67082. *
  67083. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67084. */
  67085. ShadowGenerator.QUALITY_HIGH = 0;
  67086. /**
  67087. * Reserved for PCF and PCSS
  67088. * Good tradeoff for quality/perf cross devices
  67089. *
  67090. * Execute PCF on a 3*3 kernel.
  67091. *
  67092. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67093. */
  67094. ShadowGenerator.QUALITY_MEDIUM = 1;
  67095. /**
  67096. * Reserved for PCF and PCSS
  67097. * The lowest quality but the fastest.
  67098. *
  67099. * Execute PCF on a 1*1 kernel.
  67100. *
  67101. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67102. */
  67103. ShadowGenerator.QUALITY_LOW = 2;
  67104. return ShadowGenerator;
  67105. }());
  67106. BABYLON.ShadowGenerator = ShadowGenerator;
  67107. })(BABYLON || (BABYLON = {}));
  67108. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67109. var BABYLON;
  67110. (function (BABYLON) {
  67111. var DefaultLoadingScreen = /** @class */ (function () {
  67112. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67113. if (_loadingText === void 0) { _loadingText = ""; }
  67114. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67115. var _this = this;
  67116. this._renderingCanvas = _renderingCanvas;
  67117. this._loadingText = _loadingText;
  67118. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67119. // Resize
  67120. this._resizeLoadingUI = function () {
  67121. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67122. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67123. if (!_this._loadingDiv) {
  67124. return;
  67125. }
  67126. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67127. _this._loadingDiv.style.left = canvasRect.left + "px";
  67128. _this._loadingDiv.style.top = canvasRect.top + "px";
  67129. _this._loadingDiv.style.width = canvasRect.width + "px";
  67130. _this._loadingDiv.style.height = canvasRect.height + "px";
  67131. };
  67132. }
  67133. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67134. if (this._loadingDiv) {
  67135. // Do not add a loading screen if there is already one
  67136. return;
  67137. }
  67138. this._loadingDiv = document.createElement("div");
  67139. this._loadingDiv.id = "babylonjsLoadingDiv";
  67140. this._loadingDiv.style.opacity = "0";
  67141. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67142. this._loadingDiv.style.pointerEvents = "none";
  67143. // Loading text
  67144. this._loadingTextDiv = document.createElement("div");
  67145. this._loadingTextDiv.style.position = "absolute";
  67146. this._loadingTextDiv.style.left = "0";
  67147. this._loadingTextDiv.style.top = "50%";
  67148. this._loadingTextDiv.style.marginTop = "80px";
  67149. this._loadingTextDiv.style.width = "100%";
  67150. this._loadingTextDiv.style.height = "20px";
  67151. this._loadingTextDiv.style.fontFamily = "Arial";
  67152. this._loadingTextDiv.style.fontSize = "14px";
  67153. this._loadingTextDiv.style.color = "white";
  67154. this._loadingTextDiv.style.textAlign = "center";
  67155. this._loadingTextDiv.innerHTML = "Loading";
  67156. this._loadingDiv.appendChild(this._loadingTextDiv);
  67157. //set the predefined text
  67158. this._loadingTextDiv.innerHTML = this._loadingText;
  67159. // Generating keyframes
  67160. var style = document.createElement('style');
  67161. style.type = 'text/css';
  67162. 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 }";
  67163. style.innerHTML = keyFrames;
  67164. document.getElementsByTagName('head')[0].appendChild(style);
  67165. // Loading img
  67166. var imgBack = new Image();
  67167. 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";
  67168. imgBack.style.position = "absolute";
  67169. imgBack.style.left = "50%";
  67170. imgBack.style.top = "50%";
  67171. imgBack.style.marginLeft = "-60px";
  67172. imgBack.style.marginTop = "-60px";
  67173. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67174. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67175. imgBack.style.transformOrigin = "50% 50%";
  67176. imgBack.style.webkitTransformOrigin = "50% 50%";
  67177. this._loadingDiv.appendChild(imgBack);
  67178. this._resizeLoadingUI();
  67179. window.addEventListener("resize", this._resizeLoadingUI);
  67180. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67181. document.body.appendChild(this._loadingDiv);
  67182. this._loadingDiv.style.opacity = "1";
  67183. };
  67184. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67185. var _this = this;
  67186. if (!this._loadingDiv) {
  67187. return;
  67188. }
  67189. var onTransitionEnd = function () {
  67190. if (!_this._loadingDiv) {
  67191. return;
  67192. }
  67193. document.body.removeChild(_this._loadingDiv);
  67194. window.removeEventListener("resize", _this._resizeLoadingUI);
  67195. _this._loadingDiv = null;
  67196. };
  67197. this._loadingDiv.style.opacity = "0";
  67198. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67199. };
  67200. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67201. set: function (text) {
  67202. this._loadingText = text;
  67203. if (this._loadingTextDiv) {
  67204. this._loadingTextDiv.innerHTML = this._loadingText;
  67205. }
  67206. },
  67207. enumerable: true,
  67208. configurable: true
  67209. });
  67210. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67211. get: function () {
  67212. return this._loadingDivBackgroundColor;
  67213. },
  67214. set: function (color) {
  67215. this._loadingDivBackgroundColor = color;
  67216. if (!this._loadingDiv) {
  67217. return;
  67218. }
  67219. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67220. },
  67221. enumerable: true,
  67222. configurable: true
  67223. });
  67224. return DefaultLoadingScreen;
  67225. }());
  67226. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67227. })(BABYLON || (BABYLON = {}));
  67228. //# sourceMappingURL=babylon.loadingScreen.js.map
  67229. var BABYLON;
  67230. (function (BABYLON) {
  67231. var SceneLoaderProgressEvent = /** @class */ (function () {
  67232. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67233. this.lengthComputable = lengthComputable;
  67234. this.loaded = loaded;
  67235. this.total = total;
  67236. }
  67237. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67238. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67239. };
  67240. return SceneLoaderProgressEvent;
  67241. }());
  67242. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67243. var SceneLoader = /** @class */ (function () {
  67244. function SceneLoader() {
  67245. }
  67246. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67247. get: function () {
  67248. return 0;
  67249. },
  67250. enumerable: true,
  67251. configurable: true
  67252. });
  67253. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67254. get: function () {
  67255. return 1;
  67256. },
  67257. enumerable: true,
  67258. configurable: true
  67259. });
  67260. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67261. get: function () {
  67262. return 2;
  67263. },
  67264. enumerable: true,
  67265. configurable: true
  67266. });
  67267. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67268. get: function () {
  67269. return 3;
  67270. },
  67271. enumerable: true,
  67272. configurable: true
  67273. });
  67274. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67275. get: function () {
  67276. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67277. },
  67278. set: function (value) {
  67279. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67280. },
  67281. enumerable: true,
  67282. configurable: true
  67283. });
  67284. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67285. get: function () {
  67286. return SceneLoader._ShowLoadingScreen;
  67287. },
  67288. set: function (value) {
  67289. SceneLoader._ShowLoadingScreen = value;
  67290. },
  67291. enumerable: true,
  67292. configurable: true
  67293. });
  67294. Object.defineProperty(SceneLoader, "loggingLevel", {
  67295. get: function () {
  67296. return SceneLoader._loggingLevel;
  67297. },
  67298. set: function (value) {
  67299. SceneLoader._loggingLevel = value;
  67300. },
  67301. enumerable: true,
  67302. configurable: true
  67303. });
  67304. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67305. get: function () {
  67306. return SceneLoader._CleanBoneMatrixWeights;
  67307. },
  67308. set: function (value) {
  67309. SceneLoader._CleanBoneMatrixWeights = value;
  67310. },
  67311. enumerable: true,
  67312. configurable: true
  67313. });
  67314. SceneLoader._getDefaultPlugin = function () {
  67315. return SceneLoader._registeredPlugins[".babylon"];
  67316. };
  67317. SceneLoader._getPluginForExtension = function (extension) {
  67318. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67319. if (registeredPlugin) {
  67320. return registeredPlugin;
  67321. }
  67322. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67323. return SceneLoader._getDefaultPlugin();
  67324. };
  67325. SceneLoader._getPluginForDirectLoad = function (data) {
  67326. for (var extension in SceneLoader._registeredPlugins) {
  67327. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67328. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67329. return SceneLoader._registeredPlugins[extension];
  67330. }
  67331. }
  67332. return SceneLoader._getDefaultPlugin();
  67333. };
  67334. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67335. if (sceneFilename.name) {
  67336. sceneFilename = sceneFilename.name;
  67337. }
  67338. var queryStringPosition = sceneFilename.indexOf("?");
  67339. if (queryStringPosition !== -1) {
  67340. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67341. }
  67342. var dotPosition = sceneFilename.lastIndexOf(".");
  67343. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67344. return SceneLoader._getPluginForExtension(extension);
  67345. };
  67346. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67347. SceneLoader._getDirectLoad = function (sceneFilename) {
  67348. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67349. return sceneFilename.substr(5);
  67350. }
  67351. return null;
  67352. };
  67353. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67354. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67355. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67356. var plugin;
  67357. if (registeredPlugin.plugin.createPlugin) {
  67358. plugin = registeredPlugin.plugin.createPlugin();
  67359. }
  67360. else {
  67361. plugin = registeredPlugin.plugin;
  67362. }
  67363. var useArrayBuffer = registeredPlugin.isBinary;
  67364. var database;
  67365. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67366. var dataCallback = function (data, responseURL) {
  67367. if (scene.isDisposed) {
  67368. onError("Scene has been disposed");
  67369. return;
  67370. }
  67371. scene.database = database;
  67372. onSuccess(plugin, data, responseURL);
  67373. };
  67374. var request = null;
  67375. var pluginDisposed = false;
  67376. var onDisposeObservable = plugin.onDisposeObservable;
  67377. if (onDisposeObservable) {
  67378. onDisposeObservable.add(function () {
  67379. pluginDisposed = true;
  67380. if (request) {
  67381. request.abort();
  67382. request = null;
  67383. }
  67384. onDispose();
  67385. });
  67386. }
  67387. var manifestChecked = function () {
  67388. if (pluginDisposed) {
  67389. return;
  67390. }
  67391. var url = rootUrl + sceneFilename;
  67392. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67393. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67394. } : undefined, database, useArrayBuffer, function (request, exception) {
  67395. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67396. });
  67397. };
  67398. if (directLoad) {
  67399. dataCallback(directLoad);
  67400. return plugin;
  67401. }
  67402. if (rootUrl.indexOf("file:") === -1) {
  67403. var engine = scene.getEngine();
  67404. var canUseOfflineSupport = engine.enableOfflineSupport;
  67405. if (canUseOfflineSupport) {
  67406. // Also check for exceptions
  67407. var exceptionFound = false;
  67408. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67409. var regex = _a[_i];
  67410. if (regex.test(rootUrl + sceneFilename)) {
  67411. exceptionFound = true;
  67412. break;
  67413. }
  67414. }
  67415. canUseOfflineSupport = !exceptionFound;
  67416. }
  67417. if (canUseOfflineSupport) {
  67418. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67419. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67420. }
  67421. else {
  67422. manifestChecked();
  67423. }
  67424. }
  67425. // Loading file from disk via input file or drag'n'drop
  67426. else {
  67427. var fileOrString = sceneFilename;
  67428. if (fileOrString.name) { // File
  67429. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67430. }
  67431. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67432. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67433. }
  67434. else {
  67435. onError("Unable to find file named " + sceneFilename);
  67436. }
  67437. }
  67438. return plugin;
  67439. };
  67440. // Public functions
  67441. SceneLoader.GetPluginForExtension = function (extension) {
  67442. return SceneLoader._getPluginForExtension(extension).plugin;
  67443. };
  67444. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67445. return !!SceneLoader._registeredPlugins[extension];
  67446. };
  67447. SceneLoader.RegisterPlugin = function (plugin) {
  67448. if (typeof plugin.extensions === "string") {
  67449. var extension = plugin.extensions;
  67450. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67451. plugin: plugin,
  67452. isBinary: false
  67453. };
  67454. }
  67455. else {
  67456. var extensions = plugin.extensions;
  67457. Object.keys(extensions).forEach(function (extension) {
  67458. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67459. plugin: plugin,
  67460. isBinary: extensions[extension].isBinary
  67461. };
  67462. });
  67463. }
  67464. };
  67465. /**
  67466. * Import meshes into a scene
  67467. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67468. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67469. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67470. * @param scene the instance of BABYLON.Scene to append to
  67471. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67472. * @param onProgress a callback with a progress event for each file being loaded
  67473. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67474. * @param pluginExtension the extension used to determine the plugin
  67475. * @returns The loaded plugin
  67476. */
  67477. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67478. if (sceneFilename === void 0) { sceneFilename = ""; }
  67479. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67480. if (onSuccess === void 0) { onSuccess = null; }
  67481. if (onProgress === void 0) { onProgress = null; }
  67482. if (onError === void 0) { onError = null; }
  67483. if (pluginExtension === void 0) { pluginExtension = null; }
  67484. if (!scene) {
  67485. BABYLON.Tools.Error("No scene available to import mesh to");
  67486. return null;
  67487. }
  67488. if (!sceneFilename) {
  67489. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67490. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67491. }
  67492. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67493. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67494. return null;
  67495. }
  67496. var loadingToken = {};
  67497. scene._addPendingData(loadingToken);
  67498. var disposeHandler = function () {
  67499. scene._removePendingData(loadingToken);
  67500. };
  67501. var errorHandler = function (message, exception) {
  67502. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67503. if (onError) {
  67504. onError(scene, errorMessage, exception);
  67505. }
  67506. else {
  67507. BABYLON.Tools.Error(errorMessage);
  67508. // should the exception be thrown?
  67509. }
  67510. disposeHandler();
  67511. };
  67512. var progressHandler = onProgress ? function (event) {
  67513. try {
  67514. onProgress(event);
  67515. }
  67516. catch (e) {
  67517. errorHandler("Error in onProgress callback", e);
  67518. }
  67519. } : undefined;
  67520. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67521. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67522. if (onSuccess) {
  67523. try {
  67524. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67525. }
  67526. catch (e) {
  67527. errorHandler("Error in onSuccess callback", e);
  67528. }
  67529. }
  67530. scene._removePendingData(loadingToken);
  67531. };
  67532. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67533. if (plugin.rewriteRootURL) {
  67534. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67535. }
  67536. if (sceneFilename === "") {
  67537. if (sceneFilename === "") {
  67538. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67539. }
  67540. }
  67541. if (plugin.importMesh) {
  67542. var syncedPlugin = plugin;
  67543. var meshes = new Array();
  67544. var particleSystems = new Array();
  67545. var skeletons = new Array();
  67546. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67547. return;
  67548. }
  67549. scene.loadingPluginName = plugin.name;
  67550. successHandler(meshes, particleSystems, skeletons, []);
  67551. }
  67552. else {
  67553. var asyncedPlugin = plugin;
  67554. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67555. scene.loadingPluginName = plugin.name;
  67556. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67557. }).catch(function (error) {
  67558. errorHandler(error.message, error);
  67559. });
  67560. }
  67561. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67562. };
  67563. /**
  67564. * Import meshes into a scene
  67565. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67566. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67567. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67568. * @param scene the instance of BABYLON.Scene to append to
  67569. * @param onProgress a callback with a progress event for each file being loaded
  67570. * @param pluginExtension the extension used to determine the plugin
  67571. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67572. */
  67573. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67574. if (sceneFilename === void 0) { sceneFilename = ""; }
  67575. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67576. if (onProgress === void 0) { onProgress = null; }
  67577. if (pluginExtension === void 0) { pluginExtension = null; }
  67578. return new Promise(function (resolve, reject) {
  67579. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67580. resolve({
  67581. meshes: meshes,
  67582. particleSystems: particleSystems,
  67583. skeletons: skeletons,
  67584. animationGroups: animationGroups
  67585. });
  67586. }, onProgress, function (scene, message, exception) {
  67587. reject(exception || new Error(message));
  67588. }, pluginExtension);
  67589. });
  67590. };
  67591. /**
  67592. * Load a scene
  67593. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67594. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67595. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67596. * @param onSuccess a callback with the scene when import succeeds
  67597. * @param onProgress a callback with a progress event for each file being loaded
  67598. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67599. * @param pluginExtension the extension used to determine the plugin
  67600. * @returns The loaded plugin
  67601. */
  67602. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67603. if (onSuccess === void 0) { onSuccess = null; }
  67604. if (onProgress === void 0) { onProgress = null; }
  67605. if (onError === void 0) { onError = null; }
  67606. if (pluginExtension === void 0) { pluginExtension = null; }
  67607. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67608. };
  67609. /**
  67610. * Load a scene
  67611. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67612. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67613. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67614. * @param onProgress a callback with a progress event for each file being loaded
  67615. * @param pluginExtension the extension used to determine the plugin
  67616. * @returns The loaded scene
  67617. */
  67618. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67619. if (onProgress === void 0) { onProgress = null; }
  67620. if (pluginExtension === void 0) { pluginExtension = null; }
  67621. return new Promise(function (resolve, reject) {
  67622. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67623. resolve(scene);
  67624. }, onProgress, function (scene, message, exception) {
  67625. reject(exception || new Error(message));
  67626. }, pluginExtension);
  67627. });
  67628. };
  67629. /**
  67630. * Append a scene
  67631. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67632. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67633. * @param scene is the instance of BABYLON.Scene to append to
  67634. * @param onSuccess a callback with the scene when import succeeds
  67635. * @param onProgress a callback with a progress event for each file being loaded
  67636. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67637. * @param pluginExtension the extension used to determine the plugin
  67638. * @returns The loaded plugin
  67639. */
  67640. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67641. if (sceneFilename === void 0) { sceneFilename = ""; }
  67642. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67643. if (onSuccess === void 0) { onSuccess = null; }
  67644. if (onProgress === void 0) { onProgress = null; }
  67645. if (onError === void 0) { onError = null; }
  67646. if (pluginExtension === void 0) { pluginExtension = null; }
  67647. if (!scene) {
  67648. BABYLON.Tools.Error("No scene available to append to");
  67649. return null;
  67650. }
  67651. if (!sceneFilename) {
  67652. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67653. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67654. }
  67655. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67656. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67657. return null;
  67658. }
  67659. if (SceneLoader.ShowLoadingScreen) {
  67660. scene.getEngine().displayLoadingUI();
  67661. }
  67662. var loadingToken = {};
  67663. scene._addPendingData(loadingToken);
  67664. var disposeHandler = function () {
  67665. scene._removePendingData(loadingToken);
  67666. scene.getEngine().hideLoadingUI();
  67667. };
  67668. var errorHandler = function (message, exception) {
  67669. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67670. if (onError) {
  67671. onError(scene, errorMessage, exception);
  67672. }
  67673. else {
  67674. BABYLON.Tools.Error(errorMessage);
  67675. // should the exception be thrown?
  67676. }
  67677. disposeHandler();
  67678. };
  67679. var progressHandler = onProgress ? function (event) {
  67680. try {
  67681. onProgress(event);
  67682. }
  67683. catch (e) {
  67684. errorHandler("Error in onProgress callback", e);
  67685. }
  67686. } : undefined;
  67687. var successHandler = function () {
  67688. if (onSuccess) {
  67689. try {
  67690. onSuccess(scene);
  67691. }
  67692. catch (e) {
  67693. errorHandler("Error in onSuccess callback", e);
  67694. }
  67695. }
  67696. scene._removePendingData(loadingToken);
  67697. };
  67698. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67699. if (sceneFilename === "") {
  67700. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67701. }
  67702. if (plugin.load) {
  67703. var syncedPlugin = plugin;
  67704. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67705. return;
  67706. }
  67707. scene.loadingPluginName = plugin.name;
  67708. successHandler();
  67709. }
  67710. else {
  67711. var asyncedPlugin = plugin;
  67712. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67713. scene.loadingPluginName = plugin.name;
  67714. successHandler();
  67715. }).catch(function (error) {
  67716. errorHandler(error.message, error);
  67717. });
  67718. }
  67719. if (SceneLoader.ShowLoadingScreen) {
  67720. scene.executeWhenReady(function () {
  67721. scene.getEngine().hideLoadingUI();
  67722. });
  67723. }
  67724. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67725. };
  67726. /**
  67727. * Append a scene
  67728. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67729. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67730. * @param scene is the instance of BABYLON.Scene to append to
  67731. * @param onProgress a callback with a progress event for each file being loaded
  67732. * @param pluginExtension the extension used to determine the plugin
  67733. * @returns The given scene
  67734. */
  67735. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67736. if (sceneFilename === void 0) { sceneFilename = ""; }
  67737. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67738. if (onProgress === void 0) { onProgress = null; }
  67739. if (pluginExtension === void 0) { pluginExtension = null; }
  67740. return new Promise(function (resolve, reject) {
  67741. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67742. resolve(scene);
  67743. }, onProgress, function (scene, message, exception) {
  67744. reject(exception || new Error(message));
  67745. }, pluginExtension);
  67746. });
  67747. };
  67748. /**
  67749. * Load a scene into an asset container
  67750. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67751. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67752. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67753. * @param onSuccess a callback with the scene when import succeeds
  67754. * @param onProgress a callback with a progress event for each file being loaded
  67755. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67756. * @param pluginExtension the extension used to determine the plugin
  67757. * @returns The loaded plugin
  67758. */
  67759. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67760. if (sceneFilename === void 0) { sceneFilename = ""; }
  67761. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67762. if (onSuccess === void 0) { onSuccess = null; }
  67763. if (onProgress === void 0) { onProgress = null; }
  67764. if (onError === void 0) { onError = null; }
  67765. if (pluginExtension === void 0) { pluginExtension = null; }
  67766. if (!scene) {
  67767. BABYLON.Tools.Error("No scene available to load asset container to");
  67768. return null;
  67769. }
  67770. if (!sceneFilename) {
  67771. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67772. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67773. }
  67774. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67775. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67776. return null;
  67777. }
  67778. var loadingToken = {};
  67779. scene._addPendingData(loadingToken);
  67780. var disposeHandler = function () {
  67781. scene._removePendingData(loadingToken);
  67782. };
  67783. var errorHandler = function (message, exception) {
  67784. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67785. if (onError) {
  67786. onError(scene, errorMessage, exception);
  67787. }
  67788. else {
  67789. BABYLON.Tools.Error(errorMessage);
  67790. // should the exception be thrown?
  67791. }
  67792. disposeHandler();
  67793. };
  67794. var progressHandler = onProgress ? function (event) {
  67795. try {
  67796. onProgress(event);
  67797. }
  67798. catch (e) {
  67799. errorHandler("Error in onProgress callback", e);
  67800. }
  67801. } : undefined;
  67802. var successHandler = function (assets) {
  67803. if (onSuccess) {
  67804. try {
  67805. onSuccess(assets);
  67806. }
  67807. catch (e) {
  67808. errorHandler("Error in onSuccess callback", e);
  67809. }
  67810. }
  67811. scene._removePendingData(loadingToken);
  67812. };
  67813. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67814. if (plugin.loadAssetContainer) {
  67815. var syncedPlugin = plugin;
  67816. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67817. if (!assetContainer) {
  67818. return;
  67819. }
  67820. scene.loadingPluginName = plugin.name;
  67821. successHandler(assetContainer);
  67822. }
  67823. else if (plugin.loadAssetContainerAsync) {
  67824. var asyncedPlugin = plugin;
  67825. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67826. scene.loadingPluginName = plugin.name;
  67827. successHandler(assetContainer);
  67828. }).catch(function (error) {
  67829. errorHandler(error.message, error);
  67830. });
  67831. }
  67832. else {
  67833. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67834. }
  67835. if (SceneLoader.ShowLoadingScreen) {
  67836. scene.executeWhenReady(function () {
  67837. scene.getEngine().hideLoadingUI();
  67838. });
  67839. }
  67840. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67841. };
  67842. /**
  67843. * Load a scene into an asset container
  67844. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67845. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67846. * @param scene is the instance of BABYLON.Scene to append to
  67847. * @param onProgress a callback with a progress event for each file being loaded
  67848. * @param pluginExtension the extension used to determine the plugin
  67849. * @returns The loaded asset container
  67850. */
  67851. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67852. if (sceneFilename === void 0) { sceneFilename = ""; }
  67853. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67854. if (onProgress === void 0) { onProgress = null; }
  67855. if (pluginExtension === void 0) { pluginExtension = null; }
  67856. return new Promise(function (resolve, reject) {
  67857. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67858. resolve(assetContainer);
  67859. }, onProgress, function (scene, message, exception) {
  67860. reject(exception || new Error(message));
  67861. }, pluginExtension);
  67862. });
  67863. };
  67864. // Flags
  67865. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67866. SceneLoader._ShowLoadingScreen = true;
  67867. SceneLoader._CleanBoneMatrixWeights = false;
  67868. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67869. // Members
  67870. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67871. SceneLoader._registeredPlugins = {};
  67872. return SceneLoader;
  67873. }());
  67874. BABYLON.SceneLoader = SceneLoader;
  67875. ;
  67876. })(BABYLON || (BABYLON = {}));
  67877. //# sourceMappingURL=babylon.sceneLoader.js.map
  67878. var BABYLON;
  67879. (function (BABYLON) {
  67880. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67881. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67882. var parsedMaterial = parsedData.materials[index];
  67883. if (parsedMaterial.id === id) {
  67884. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67885. }
  67886. }
  67887. return null;
  67888. };
  67889. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67890. for (var i in names) {
  67891. if (mesh.name === names[i]) {
  67892. hierarchyIds.push(mesh.id);
  67893. return true;
  67894. }
  67895. }
  67896. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67897. hierarchyIds.push(mesh.id);
  67898. return true;
  67899. }
  67900. return false;
  67901. };
  67902. var logOperation = function (operation, producer) {
  67903. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67904. };
  67905. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67906. if (addToScene === void 0) { addToScene = false; }
  67907. var container = new BABYLON.AssetContainer(scene);
  67908. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67909. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67910. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67911. // and avoid problems with multiple concurrent .babylon loads.
  67912. var log = "importScene has failed JSON parse";
  67913. try {
  67914. var parsedData = JSON.parse(data);
  67915. log = "";
  67916. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67917. var index;
  67918. var cache;
  67919. // Lights
  67920. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67921. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67922. var parsedLight = parsedData.lights[index];
  67923. var light = BABYLON.Light.Parse(parsedLight, scene);
  67924. if (light) {
  67925. container.lights.push(light);
  67926. log += (index === 0 ? "\n\tLights:" : "");
  67927. log += "\n\t\t" + light.toString(fullDetails);
  67928. }
  67929. }
  67930. }
  67931. // Animations
  67932. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67933. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67934. var parsedAnimation = parsedData.animations[index];
  67935. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67936. scene.animations.push(animation);
  67937. container.animations.push(animation);
  67938. log += (index === 0 ? "\n\tAnimations:" : "");
  67939. log += "\n\t\t" + animation.toString(fullDetails);
  67940. }
  67941. }
  67942. // Materials
  67943. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67944. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67945. var parsedMaterial = parsedData.materials[index];
  67946. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67947. container.materials.push(mat);
  67948. log += (index === 0 ? "\n\tMaterials:" : "");
  67949. log += "\n\t\t" + mat.toString(fullDetails);
  67950. }
  67951. }
  67952. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67953. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67954. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67955. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67956. container.multiMaterials.push(mmat);
  67957. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67958. log += "\n\t\t" + mmat.toString(fullDetails);
  67959. }
  67960. }
  67961. // Morph targets
  67962. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67963. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67964. var managerData = _a[_i];
  67965. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67966. }
  67967. }
  67968. // Skeletons
  67969. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67970. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67971. var parsedSkeleton = parsedData.skeletons[index];
  67972. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67973. container.skeletons.push(skeleton);
  67974. log += (index === 0 ? "\n\tSkeletons:" : "");
  67975. log += "\n\t\t" + skeleton.toString(fullDetails);
  67976. }
  67977. }
  67978. // Geometries
  67979. var geometries = parsedData.geometries;
  67980. if (geometries !== undefined && geometries !== null) {
  67981. var addedGeometry = new Array();
  67982. // Boxes
  67983. var boxes = geometries.boxes;
  67984. if (boxes !== undefined && boxes !== null) {
  67985. for (index = 0, cache = boxes.length; index < cache; index++) {
  67986. var parsedBox = boxes[index];
  67987. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67988. }
  67989. }
  67990. // Spheres
  67991. var spheres = geometries.spheres;
  67992. if (spheres !== undefined && spheres !== null) {
  67993. for (index = 0, cache = spheres.length; index < cache; index++) {
  67994. var parsedSphere = spheres[index];
  67995. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67996. }
  67997. }
  67998. // Cylinders
  67999. var cylinders = geometries.cylinders;
  68000. if (cylinders !== undefined && cylinders !== null) {
  68001. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68002. var parsedCylinder = cylinders[index];
  68003. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68004. }
  68005. }
  68006. // Toruses
  68007. var toruses = geometries.toruses;
  68008. if (toruses !== undefined && toruses !== null) {
  68009. for (index = 0, cache = toruses.length; index < cache; index++) {
  68010. var parsedTorus = toruses[index];
  68011. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68012. }
  68013. }
  68014. // Grounds
  68015. var grounds = geometries.grounds;
  68016. if (grounds !== undefined && grounds !== null) {
  68017. for (index = 0, cache = grounds.length; index < cache; index++) {
  68018. var parsedGround = grounds[index];
  68019. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68020. }
  68021. }
  68022. // Planes
  68023. var planes = geometries.planes;
  68024. if (planes !== undefined && planes !== null) {
  68025. for (index = 0, cache = planes.length; index < cache; index++) {
  68026. var parsedPlane = planes[index];
  68027. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68028. }
  68029. }
  68030. // TorusKnots
  68031. var torusKnots = geometries.torusKnots;
  68032. if (torusKnots !== undefined && torusKnots !== null) {
  68033. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68034. var parsedTorusKnot = torusKnots[index];
  68035. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68036. }
  68037. }
  68038. // VertexData
  68039. var vertexData = geometries.vertexData;
  68040. if (vertexData !== undefined && vertexData !== null) {
  68041. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68042. var parsedVertexData = vertexData[index];
  68043. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68044. }
  68045. }
  68046. addedGeometry.forEach(function (g) {
  68047. if (g) {
  68048. container.geometries.push(g);
  68049. }
  68050. });
  68051. }
  68052. // Transform nodes
  68053. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68054. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68055. var parsedTransformNode = parsedData.transformNodes[index];
  68056. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68057. container.transformNodes.push(node);
  68058. }
  68059. }
  68060. // Meshes
  68061. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68062. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68063. var parsedMesh = parsedData.meshes[index];
  68064. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68065. container.meshes.push(mesh);
  68066. log += (index === 0 ? "\n\tMeshes:" : "");
  68067. log += "\n\t\t" + mesh.toString(fullDetails);
  68068. }
  68069. }
  68070. // Cameras
  68071. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68072. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68073. var parsedCamera = parsedData.cameras[index];
  68074. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68075. container.cameras.push(camera);
  68076. log += (index === 0 ? "\n\tCameras:" : "");
  68077. log += "\n\t\t" + camera.toString(fullDetails);
  68078. }
  68079. }
  68080. // Browsing all the graph to connect the dots
  68081. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68082. var camera = scene.cameras[index];
  68083. if (camera._waitingParentId) {
  68084. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68085. camera._waitingParentId = null;
  68086. }
  68087. }
  68088. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68089. var light_1 = scene.lights[index];
  68090. if (light_1 && light_1._waitingParentId) {
  68091. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68092. light_1._waitingParentId = null;
  68093. }
  68094. }
  68095. // Sounds
  68096. // TODO: add sound
  68097. var loadedSounds = [];
  68098. var loadedSound;
  68099. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68100. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68101. var parsedSound = parsedData.sounds[index];
  68102. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68103. if (!parsedSound.url)
  68104. parsedSound.url = parsedSound.name;
  68105. if (!loadedSounds[parsedSound.url]) {
  68106. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68107. loadedSounds[parsedSound.url] = loadedSound;
  68108. container.sounds.push(loadedSound);
  68109. }
  68110. else {
  68111. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68112. }
  68113. }
  68114. else {
  68115. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68116. }
  68117. }
  68118. }
  68119. loadedSounds = [];
  68120. // Connect parents & children and parse actions
  68121. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68122. var transformNode = scene.transformNodes[index];
  68123. if (transformNode._waitingParentId) {
  68124. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68125. transformNode._waitingParentId = null;
  68126. }
  68127. }
  68128. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68129. var mesh = scene.meshes[index];
  68130. if (mesh._waitingParentId) {
  68131. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68132. mesh._waitingParentId = null;
  68133. }
  68134. if (mesh._waitingActions) {
  68135. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68136. mesh._waitingActions = null;
  68137. }
  68138. }
  68139. // freeze world matrix application
  68140. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68141. var currentMesh = scene.meshes[index];
  68142. if (currentMesh._waitingFreezeWorldMatrix) {
  68143. currentMesh.freezeWorldMatrix();
  68144. currentMesh._waitingFreezeWorldMatrix = null;
  68145. }
  68146. else {
  68147. currentMesh.computeWorldMatrix(true);
  68148. }
  68149. }
  68150. // Particles Systems
  68151. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68152. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68153. var parsedParticleSystem = parsedData.particleSystems[index];
  68154. if (parsedParticleSystem.activeParticleCount) {
  68155. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68156. container.particleSystems.push(ps);
  68157. }
  68158. else {
  68159. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68160. container.particleSystems.push(ps);
  68161. }
  68162. }
  68163. }
  68164. // Lens flares
  68165. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68166. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68167. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68168. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68169. container.lensFlareSystems.push(lf);
  68170. }
  68171. }
  68172. // Shadows
  68173. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68174. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68175. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68176. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68177. container.shadowGenerators.push(sg);
  68178. }
  68179. }
  68180. // Lights exclusions / inclusions
  68181. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68182. var light_2 = scene.lights[index];
  68183. // Excluded check
  68184. if (light_2._excludedMeshesIds.length > 0) {
  68185. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68186. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68187. if (excludedMesh) {
  68188. light_2.excludedMeshes.push(excludedMesh);
  68189. }
  68190. }
  68191. light_2._excludedMeshesIds = [];
  68192. }
  68193. // Included check
  68194. if (light_2._includedOnlyMeshesIds.length > 0) {
  68195. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68196. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68197. if (includedOnlyMesh) {
  68198. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68199. }
  68200. }
  68201. light_2._includedOnlyMeshesIds = [];
  68202. }
  68203. }
  68204. // Effect layers
  68205. if (parsedData.effectLayers) {
  68206. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68207. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68208. container.effectLayers.push(effectLayer);
  68209. }
  68210. }
  68211. // Actions (scene)
  68212. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68213. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68214. }
  68215. if (!addToScene) {
  68216. container.removeAllFromScene();
  68217. }
  68218. }
  68219. catch (err) {
  68220. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68221. if (onError) {
  68222. onError(msg, err);
  68223. }
  68224. else {
  68225. BABYLON.Tools.Log(msg);
  68226. throw err;
  68227. }
  68228. }
  68229. finally {
  68230. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68231. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68232. }
  68233. }
  68234. return container;
  68235. };
  68236. BABYLON.SceneLoader.RegisterPlugin({
  68237. name: "babylon.js",
  68238. extensions: ".babylon",
  68239. canDirectLoad: function (data) {
  68240. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68241. return true;
  68242. }
  68243. return false;
  68244. },
  68245. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68246. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68247. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68248. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68249. // and avoid problems with multiple concurrent .babylon loads.
  68250. var log = "importMesh has failed JSON parse";
  68251. try {
  68252. var parsedData = JSON.parse(data);
  68253. log = "";
  68254. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68255. if (!meshesNames) {
  68256. meshesNames = null;
  68257. }
  68258. else if (!Array.isArray(meshesNames)) {
  68259. meshesNames = [meshesNames];
  68260. }
  68261. var hierarchyIds = new Array();
  68262. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68263. var loadedSkeletonsIds = [];
  68264. var loadedMaterialsIds = [];
  68265. var index;
  68266. var cache;
  68267. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68268. var parsedMesh = parsedData.meshes[index];
  68269. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68270. if (meshesNames !== null) {
  68271. // Remove found mesh name from list.
  68272. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68273. }
  68274. //Geometry?
  68275. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68276. //does the file contain geometries?
  68277. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68278. //find the correct geometry and add it to the scene
  68279. var found = false;
  68280. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68281. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68282. return;
  68283. }
  68284. else {
  68285. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68286. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68287. switch (geometryType) {
  68288. case "boxes":
  68289. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68290. break;
  68291. case "spheres":
  68292. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68293. break;
  68294. case "cylinders":
  68295. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68296. break;
  68297. case "toruses":
  68298. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68299. break;
  68300. case "grounds":
  68301. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68302. break;
  68303. case "planes":
  68304. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68305. break;
  68306. case "torusKnots":
  68307. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68308. break;
  68309. case "vertexData":
  68310. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68311. break;
  68312. }
  68313. found = true;
  68314. }
  68315. });
  68316. }
  68317. });
  68318. if (found === false) {
  68319. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68320. }
  68321. }
  68322. }
  68323. // Material ?
  68324. if (parsedMesh.materialId) {
  68325. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68326. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68327. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68328. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68329. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68330. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68331. var subMatId = parsedMultiMaterial.materials[matIndex];
  68332. loadedMaterialsIds.push(subMatId);
  68333. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68334. if (mat) {
  68335. log += "\n\tMaterial " + mat.toString(fullDetails);
  68336. }
  68337. }
  68338. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68339. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68340. if (mmat) {
  68341. materialFound = true;
  68342. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68343. }
  68344. break;
  68345. }
  68346. }
  68347. }
  68348. if (materialFound === false) {
  68349. loadedMaterialsIds.push(parsedMesh.materialId);
  68350. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68351. if (!mat) {
  68352. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68353. }
  68354. else {
  68355. log += "\n\tMaterial " + mat.toString(fullDetails);
  68356. }
  68357. }
  68358. }
  68359. // Skeleton ?
  68360. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68361. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68362. if (skeletonAlreadyLoaded === false) {
  68363. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68364. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68365. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68366. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68367. skeletons.push(skeleton);
  68368. loadedSkeletonsIds.push(parsedSkeleton.id);
  68369. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68370. }
  68371. }
  68372. }
  68373. }
  68374. // Morph targets ?
  68375. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68376. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68377. var managerData = _a[_i];
  68378. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68379. }
  68380. }
  68381. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68382. meshes.push(mesh);
  68383. log += "\n\tMesh " + mesh.toString(fullDetails);
  68384. }
  68385. }
  68386. // Connecting parents
  68387. var currentMesh;
  68388. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68389. currentMesh = scene.meshes[index];
  68390. if (currentMesh._waitingParentId) {
  68391. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68392. currentMesh._waitingParentId = null;
  68393. }
  68394. }
  68395. // freeze and compute world matrix application
  68396. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68397. currentMesh = scene.meshes[index];
  68398. if (currentMesh._waitingFreezeWorldMatrix) {
  68399. currentMesh.freezeWorldMatrix();
  68400. currentMesh._waitingFreezeWorldMatrix = null;
  68401. }
  68402. else {
  68403. currentMesh.computeWorldMatrix(true);
  68404. }
  68405. }
  68406. }
  68407. // Particles
  68408. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68409. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68410. var parsedParticleSystem = parsedData.particleSystems[index];
  68411. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68412. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68413. }
  68414. }
  68415. }
  68416. return true;
  68417. }
  68418. catch (err) {
  68419. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68420. if (onError) {
  68421. onError(msg, err);
  68422. }
  68423. else {
  68424. BABYLON.Tools.Log(msg);
  68425. throw err;
  68426. }
  68427. }
  68428. finally {
  68429. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68430. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68431. }
  68432. }
  68433. return false;
  68434. },
  68435. load: function (scene, data, rootUrl, onError) {
  68436. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68437. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68438. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68439. // and avoid problems with multiple concurrent .babylon loads.
  68440. var log = "importScene has failed JSON parse";
  68441. try {
  68442. var parsedData = JSON.parse(data);
  68443. log = "";
  68444. // Scene
  68445. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68446. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68447. }
  68448. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68449. scene.autoClear = parsedData.autoClear;
  68450. }
  68451. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68452. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68453. }
  68454. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68455. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68456. }
  68457. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68458. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68459. }
  68460. // Fog
  68461. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68462. scene.fogMode = parsedData.fogMode;
  68463. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68464. scene.fogStart = parsedData.fogStart;
  68465. scene.fogEnd = parsedData.fogEnd;
  68466. scene.fogDensity = parsedData.fogDensity;
  68467. log += "\tFog mode for scene: ";
  68468. switch (scene.fogMode) {
  68469. // getters not compiling, so using hardcoded
  68470. case 1:
  68471. log += "exp\n";
  68472. break;
  68473. case 2:
  68474. log += "exp2\n";
  68475. break;
  68476. case 3:
  68477. log += "linear\n";
  68478. break;
  68479. }
  68480. }
  68481. //Physics
  68482. if (parsedData.physicsEnabled) {
  68483. var physicsPlugin;
  68484. if (parsedData.physicsEngine === "cannon") {
  68485. physicsPlugin = new BABYLON.CannonJSPlugin();
  68486. }
  68487. else if (parsedData.physicsEngine === "oimo") {
  68488. physicsPlugin = new BABYLON.OimoJSPlugin();
  68489. }
  68490. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68491. //else - default engine, which is currently oimo
  68492. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68493. scene.enablePhysics(physicsGravity, physicsPlugin);
  68494. }
  68495. // Metadata
  68496. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68497. scene.metadata = parsedData.metadata;
  68498. }
  68499. //collisions, if defined. otherwise, default is true
  68500. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68501. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68502. }
  68503. scene.workerCollisions = !!parsedData.workerCollisions;
  68504. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68505. if (!container) {
  68506. return false;
  68507. }
  68508. if (parsedData.autoAnimate) {
  68509. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68510. }
  68511. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68512. scene.setActiveCameraByID(parsedData.activeCameraID);
  68513. }
  68514. // Environment texture
  68515. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68516. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68517. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68518. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68519. if (parsedData.environmentTextureRotationY) {
  68520. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68521. }
  68522. scene.environmentTexture = hdrTexture;
  68523. }
  68524. else {
  68525. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68526. if (parsedData.environmentTextureRotationY) {
  68527. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68528. }
  68529. scene.environmentTexture = cubeTexture;
  68530. }
  68531. if (parsedData.createDefaultSkybox === true) {
  68532. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68533. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68534. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68535. }
  68536. }
  68537. // Finish
  68538. return true;
  68539. }
  68540. catch (err) {
  68541. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68542. if (onError) {
  68543. onError(msg, err);
  68544. }
  68545. else {
  68546. BABYLON.Tools.Log(msg);
  68547. throw err;
  68548. }
  68549. }
  68550. finally {
  68551. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68552. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68553. }
  68554. }
  68555. return false;
  68556. },
  68557. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68558. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68559. return container;
  68560. }
  68561. });
  68562. })(BABYLON || (BABYLON = {}));
  68563. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68564. var BABYLON;
  68565. (function (BABYLON) {
  68566. var FilesInput = /** @class */ (function () {
  68567. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68568. this.onProcessFileCallback = function () { return true; };
  68569. this._engine = engine;
  68570. this._currentScene = scene;
  68571. this._sceneLoadedCallback = sceneLoadedCallback;
  68572. this._progressCallback = progressCallback;
  68573. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68574. this._textureLoadingCallback = textureLoadingCallback;
  68575. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68576. this._onReloadCallback = onReloadCallback;
  68577. this._errorCallback = errorCallback;
  68578. }
  68579. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68580. var _this = this;
  68581. if (elementToMonitor) {
  68582. this._elementToMonitor = elementToMonitor;
  68583. this._dragEnterHandler = function (e) { _this.drag(e); };
  68584. this._dragOverHandler = function (e) { _this.drag(e); };
  68585. this._dropHandler = function (e) { _this.drop(e); };
  68586. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68587. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68588. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68589. }
  68590. };
  68591. FilesInput.prototype.dispose = function () {
  68592. if (!this._elementToMonitor) {
  68593. return;
  68594. }
  68595. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68596. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68597. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68598. };
  68599. FilesInput.prototype.renderFunction = function () {
  68600. if (this._additionalRenderLoopLogicCallback) {
  68601. this._additionalRenderLoopLogicCallback();
  68602. }
  68603. if (this._currentScene) {
  68604. if (this._textureLoadingCallback) {
  68605. var remaining = this._currentScene.getWaitingItemsCount();
  68606. if (remaining > 0) {
  68607. this._textureLoadingCallback(remaining);
  68608. }
  68609. }
  68610. this._currentScene.render();
  68611. }
  68612. };
  68613. FilesInput.prototype.drag = function (e) {
  68614. e.stopPropagation();
  68615. e.preventDefault();
  68616. };
  68617. FilesInput.prototype.drop = function (eventDrop) {
  68618. eventDrop.stopPropagation();
  68619. eventDrop.preventDefault();
  68620. this.loadFiles(eventDrop);
  68621. };
  68622. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68623. var _this = this;
  68624. var reader = folder.createReader();
  68625. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68626. reader.readEntries(function (entries) {
  68627. remaining.count += entries.length;
  68628. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68629. var entry = entries_1[_i];
  68630. if (entry.isFile) {
  68631. entry.file(function (file) {
  68632. file.correctName = relativePath + file.name;
  68633. files.push(file);
  68634. if (--remaining.count === 0) {
  68635. callback();
  68636. }
  68637. });
  68638. }
  68639. else if (entry.isDirectory) {
  68640. _this._traverseFolder(entry, files, remaining, callback);
  68641. }
  68642. }
  68643. if (--remaining.count) {
  68644. callback();
  68645. }
  68646. });
  68647. };
  68648. FilesInput.prototype._processFiles = function (files) {
  68649. for (var i = 0; i < files.length; i++) {
  68650. var name = files[i].correctName.toLowerCase();
  68651. var extension = name.split('.').pop();
  68652. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68653. continue;
  68654. }
  68655. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68656. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68657. this._sceneFileToLoad = files[i];
  68658. }
  68659. else {
  68660. FilesInput.FilesToLoad[name] = files[i];
  68661. }
  68662. }
  68663. };
  68664. FilesInput.prototype.loadFiles = function (event) {
  68665. var _this = this;
  68666. if (this._startingProcessingFilesCallback)
  68667. this._startingProcessingFilesCallback();
  68668. // Handling data transfer via drag'n'drop
  68669. if (event && event.dataTransfer && event.dataTransfer.files) {
  68670. this._filesToLoad = event.dataTransfer.files;
  68671. }
  68672. // Handling files from input files
  68673. if (event && event.target && event.target.files) {
  68674. this._filesToLoad = event.target.files;
  68675. }
  68676. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68677. var files_1 = new Array();
  68678. var folders = [];
  68679. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68680. for (var i = 0; i < this._filesToLoad.length; i++) {
  68681. var fileToLoad = this._filesToLoad[i];
  68682. var name_1 = fileToLoad.name.toLowerCase();
  68683. var entry = void 0;
  68684. fileToLoad.correctName = name_1;
  68685. if (items) {
  68686. var item = items[i];
  68687. if (item.getAsEntry) {
  68688. entry = item.getAsEntry();
  68689. }
  68690. else if (item.webkitGetAsEntry) {
  68691. entry = item.webkitGetAsEntry();
  68692. }
  68693. }
  68694. if (!entry) {
  68695. files_1.push(fileToLoad);
  68696. }
  68697. else {
  68698. if (entry.isDirectory) {
  68699. folders.push(entry);
  68700. }
  68701. else {
  68702. files_1.push(fileToLoad);
  68703. }
  68704. }
  68705. }
  68706. if (folders.length === 0) {
  68707. this._processFiles(files_1);
  68708. this._processReload();
  68709. }
  68710. else {
  68711. var remaining = { count: folders.length };
  68712. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68713. var folder = folders_1[_i];
  68714. this._traverseFolder(folder, files_1, remaining, function () {
  68715. _this._processFiles(files_1);
  68716. if (remaining.count === 0) {
  68717. _this._processReload();
  68718. }
  68719. });
  68720. }
  68721. }
  68722. }
  68723. };
  68724. FilesInput.prototype._processReload = function () {
  68725. if (this._onReloadCallback) {
  68726. this._onReloadCallback(this._sceneFileToLoad);
  68727. }
  68728. else {
  68729. this.reload();
  68730. }
  68731. };
  68732. FilesInput.prototype.reload = function () {
  68733. var _this = this;
  68734. // If a scene file has been provided
  68735. if (this._sceneFileToLoad) {
  68736. if (this._currentScene) {
  68737. if (BABYLON.Tools.errorsCount > 0) {
  68738. BABYLON.Tools.ClearLogCache();
  68739. }
  68740. this._engine.stopRenderLoop();
  68741. }
  68742. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68743. if (_this._progressCallback) {
  68744. _this._progressCallback(progress);
  68745. }
  68746. }).then(function (scene) {
  68747. if (_this._currentScene) {
  68748. _this._currentScene.dispose();
  68749. }
  68750. _this._currentScene = scene;
  68751. if (_this._sceneLoadedCallback) {
  68752. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68753. }
  68754. // Wait for textures and shaders to be ready
  68755. _this._currentScene.executeWhenReady(function () {
  68756. _this._engine.runRenderLoop(function () {
  68757. _this.renderFunction();
  68758. });
  68759. });
  68760. }).catch(function (error) {
  68761. if (_this._errorCallback) {
  68762. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68763. }
  68764. });
  68765. }
  68766. else {
  68767. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68768. }
  68769. };
  68770. FilesInput.FilesToLoad = {};
  68771. return FilesInput;
  68772. }());
  68773. BABYLON.FilesInput = FilesInput;
  68774. })(BABYLON || (BABYLON = {}));
  68775. //# sourceMappingURL=babylon.filesInput.js.map
  68776. var BABYLON;
  68777. (function (BABYLON) {
  68778. /**
  68779. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68780. * The underlying implementation relies on an associative array to ensure the best performances.
  68781. * The value can be anything including 'null' but except 'undefined'
  68782. */
  68783. var StringDictionary = /** @class */ (function () {
  68784. function StringDictionary() {
  68785. this._count = 0;
  68786. this._data = {};
  68787. }
  68788. /**
  68789. * This will clear this dictionary and copy the content from the 'source' one.
  68790. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68791. * @param source the dictionary to take the content from and copy to this dictionary
  68792. */
  68793. StringDictionary.prototype.copyFrom = function (source) {
  68794. var _this = this;
  68795. this.clear();
  68796. source.forEach(function (t, v) { return _this.add(t, v); });
  68797. };
  68798. /**
  68799. * Get a value based from its key
  68800. * @param key the given key to get the matching value from
  68801. * @return the value if found, otherwise undefined is returned
  68802. */
  68803. StringDictionary.prototype.get = function (key) {
  68804. var val = this._data[key];
  68805. if (val !== undefined) {
  68806. return val;
  68807. }
  68808. return undefined;
  68809. };
  68810. /**
  68811. * Get a value from its key or add it if it doesn't exist.
  68812. * This method will ensure you that a given key/data will be present in the dictionary.
  68813. * @param key the given key to get the matching value from
  68814. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68815. * The factory will only be invoked if there's no data for the given key.
  68816. * @return the value corresponding to the key.
  68817. */
  68818. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68819. var val = this.get(key);
  68820. if (val !== undefined) {
  68821. return val;
  68822. }
  68823. val = factory(key);
  68824. if (val) {
  68825. this.add(key, val);
  68826. }
  68827. return val;
  68828. };
  68829. /**
  68830. * Get a value from its key if present in the dictionary otherwise add it
  68831. * @param key the key to get the value from
  68832. * @param val if there's no such key/value pair in the dictionary add it with this value
  68833. * @return the value corresponding to the key
  68834. */
  68835. StringDictionary.prototype.getOrAdd = function (key, val) {
  68836. var curVal = this.get(key);
  68837. if (curVal !== undefined) {
  68838. return curVal;
  68839. }
  68840. this.add(key, val);
  68841. return val;
  68842. };
  68843. /**
  68844. * Check if there's a given key in the dictionary
  68845. * @param key the key to check for
  68846. * @return true if the key is present, false otherwise
  68847. */
  68848. StringDictionary.prototype.contains = function (key) {
  68849. return this._data[key] !== undefined;
  68850. };
  68851. /**
  68852. * Add a new key and its corresponding value
  68853. * @param key the key to add
  68854. * @param value the value corresponding to the key
  68855. * @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
  68856. */
  68857. StringDictionary.prototype.add = function (key, value) {
  68858. if (this._data[key] !== undefined) {
  68859. return false;
  68860. }
  68861. this._data[key] = value;
  68862. ++this._count;
  68863. return true;
  68864. };
  68865. StringDictionary.prototype.set = function (key, value) {
  68866. if (this._data[key] === undefined) {
  68867. return false;
  68868. }
  68869. this._data[key] = value;
  68870. return true;
  68871. };
  68872. /**
  68873. * Get the element of the given key and remove it from the dictionary
  68874. * @param key
  68875. */
  68876. StringDictionary.prototype.getAndRemove = function (key) {
  68877. var val = this.get(key);
  68878. if (val !== undefined) {
  68879. delete this._data[key];
  68880. --this._count;
  68881. return val;
  68882. }
  68883. return null;
  68884. };
  68885. /**
  68886. * Remove a key/value from the dictionary.
  68887. * @param key the key to remove
  68888. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68889. */
  68890. StringDictionary.prototype.remove = function (key) {
  68891. if (this.contains(key)) {
  68892. delete this._data[key];
  68893. --this._count;
  68894. return true;
  68895. }
  68896. return false;
  68897. };
  68898. /**
  68899. * Clear the whole content of the dictionary
  68900. */
  68901. StringDictionary.prototype.clear = function () {
  68902. this._data = {};
  68903. this._count = 0;
  68904. };
  68905. Object.defineProperty(StringDictionary.prototype, "count", {
  68906. get: function () {
  68907. return this._count;
  68908. },
  68909. enumerable: true,
  68910. configurable: true
  68911. });
  68912. /**
  68913. * Execute a callback on each key/val of the dictionary.
  68914. * Note that you can remove any element in this dictionary in the callback implementation
  68915. * @param callback the callback to execute on a given key/value pair
  68916. */
  68917. StringDictionary.prototype.forEach = function (callback) {
  68918. for (var cur in this._data) {
  68919. var val = this._data[cur];
  68920. callback(cur, val);
  68921. }
  68922. };
  68923. /**
  68924. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68925. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68926. * Note that you can remove any element in this dictionary in the callback implementation
  68927. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68928. */
  68929. StringDictionary.prototype.first = function (callback) {
  68930. for (var cur in this._data) {
  68931. var val = this._data[cur];
  68932. var res = callback(cur, val);
  68933. if (res) {
  68934. return res;
  68935. }
  68936. }
  68937. return null;
  68938. };
  68939. return StringDictionary;
  68940. }());
  68941. BABYLON.StringDictionary = StringDictionary;
  68942. })(BABYLON || (BABYLON = {}));
  68943. //# sourceMappingURL=babylon.stringDictionary.js.map
  68944. var BABYLON;
  68945. (function (BABYLON) {
  68946. var Tags = /** @class */ (function () {
  68947. function Tags() {
  68948. }
  68949. Tags.EnableFor = function (obj) {
  68950. obj._tags = obj._tags || {};
  68951. obj.hasTags = function () {
  68952. return Tags.HasTags(obj);
  68953. };
  68954. obj.addTags = function (tagsString) {
  68955. return Tags.AddTagsTo(obj, tagsString);
  68956. };
  68957. obj.removeTags = function (tagsString) {
  68958. return Tags.RemoveTagsFrom(obj, tagsString);
  68959. };
  68960. obj.matchesTagsQuery = function (tagsQuery) {
  68961. return Tags.MatchesQuery(obj, tagsQuery);
  68962. };
  68963. };
  68964. Tags.DisableFor = function (obj) {
  68965. delete obj._tags;
  68966. delete obj.hasTags;
  68967. delete obj.addTags;
  68968. delete obj.removeTags;
  68969. delete obj.matchesTagsQuery;
  68970. };
  68971. Tags.HasTags = function (obj) {
  68972. if (!obj._tags) {
  68973. return false;
  68974. }
  68975. return !BABYLON.Tools.IsEmpty(obj._tags);
  68976. };
  68977. Tags.GetTags = function (obj, asString) {
  68978. if (asString === void 0) { asString = true; }
  68979. if (!obj._tags) {
  68980. return null;
  68981. }
  68982. if (asString) {
  68983. var tagsArray = [];
  68984. for (var tag in obj._tags) {
  68985. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68986. tagsArray.push(tag);
  68987. }
  68988. }
  68989. return tagsArray.join(" ");
  68990. }
  68991. else {
  68992. return obj._tags;
  68993. }
  68994. };
  68995. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68996. // a tag cannot start with '||', '&&', and '!'
  68997. // it cannot contain whitespaces
  68998. Tags.AddTagsTo = function (obj, tagsString) {
  68999. if (!tagsString) {
  69000. return;
  69001. }
  69002. if (typeof tagsString !== "string") {
  69003. return;
  69004. }
  69005. var tags = tagsString.split(" ");
  69006. tags.forEach(function (tag, index, array) {
  69007. Tags._AddTagTo(obj, tag);
  69008. });
  69009. };
  69010. Tags._AddTagTo = function (obj, tag) {
  69011. tag = tag.trim();
  69012. if (tag === "" || tag === "true" || tag === "false") {
  69013. return;
  69014. }
  69015. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69016. return;
  69017. }
  69018. Tags.EnableFor(obj);
  69019. obj._tags[tag] = true;
  69020. };
  69021. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69022. if (!Tags.HasTags(obj)) {
  69023. return;
  69024. }
  69025. var tags = tagsString.split(" ");
  69026. for (var t in tags) {
  69027. Tags._RemoveTagFrom(obj, tags[t]);
  69028. }
  69029. };
  69030. Tags._RemoveTagFrom = function (obj, tag) {
  69031. delete obj._tags[tag];
  69032. };
  69033. Tags.MatchesQuery = function (obj, tagsQuery) {
  69034. if (tagsQuery === undefined) {
  69035. return true;
  69036. }
  69037. if (tagsQuery === "") {
  69038. return Tags.HasTags(obj);
  69039. }
  69040. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69041. };
  69042. return Tags;
  69043. }());
  69044. BABYLON.Tags = Tags;
  69045. })(BABYLON || (BABYLON = {}));
  69046. //# sourceMappingURL=babylon.tags.js.map
  69047. var BABYLON;
  69048. (function (BABYLON) {
  69049. /**
  69050. * Class used to evalaute queries containing `and` and `or` operators
  69051. */
  69052. var AndOrNotEvaluator = /** @class */ (function () {
  69053. function AndOrNotEvaluator() {
  69054. }
  69055. /**
  69056. * Evaluate a query
  69057. * @param query defines the query to evaluate
  69058. * @param evaluateCallback defines the callback used to filter result
  69059. * @returns true if the query matches
  69060. */
  69061. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69062. if (!query.match(/\([^\(\)]*\)/g)) {
  69063. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69064. }
  69065. else {
  69066. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69067. // remove parenthesis
  69068. r = r.slice(1, r.length - 1);
  69069. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69070. });
  69071. }
  69072. if (query === "true") {
  69073. return true;
  69074. }
  69075. if (query === "false") {
  69076. return false;
  69077. }
  69078. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69079. };
  69080. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69081. evaluateCallback = evaluateCallback || (function (r) {
  69082. return r === "true" ? true : false;
  69083. });
  69084. var result;
  69085. var or = parenthesisContent.split("||");
  69086. for (var i in or) {
  69087. if (or.hasOwnProperty(i)) {
  69088. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69089. var and = ori.split("&&");
  69090. if (and.length > 1) {
  69091. for (var j = 0; j < and.length; ++j) {
  69092. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69093. if (andj !== "true" && andj !== "false") {
  69094. if (andj[0] === "!") {
  69095. result = !evaluateCallback(andj.substring(1));
  69096. }
  69097. else {
  69098. result = evaluateCallback(andj);
  69099. }
  69100. }
  69101. else {
  69102. result = andj === "true" ? true : false;
  69103. }
  69104. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69105. ori = "false";
  69106. break;
  69107. }
  69108. }
  69109. }
  69110. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69111. result = true;
  69112. break;
  69113. }
  69114. // result equals false (or undefined)
  69115. if (ori !== "true" && ori !== "false") {
  69116. if (ori[0] === "!") {
  69117. result = !evaluateCallback(ori.substring(1));
  69118. }
  69119. else {
  69120. result = evaluateCallback(ori);
  69121. }
  69122. }
  69123. else {
  69124. result = ori === "true" ? true : false;
  69125. }
  69126. }
  69127. }
  69128. // the whole parenthesis scope is replaced by 'true' or 'false'
  69129. return result ? "true" : "false";
  69130. };
  69131. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69132. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69133. // remove whitespaces
  69134. r = r.replace(/[\s]/g, function () { return ""; });
  69135. return r.length % 2 ? "!" : "";
  69136. });
  69137. booleanString = booleanString.trim();
  69138. if (booleanString === "!true") {
  69139. booleanString = "false";
  69140. }
  69141. else if (booleanString === "!false") {
  69142. booleanString = "true";
  69143. }
  69144. return booleanString;
  69145. };
  69146. return AndOrNotEvaluator;
  69147. }());
  69148. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69149. })(BABYLON || (BABYLON = {}));
  69150. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69151. var BABYLON;
  69152. (function (BABYLON) {
  69153. /**
  69154. * Class used to enable access to IndexedDB
  69155. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69156. */
  69157. var Database = /** @class */ (function () {
  69158. /**
  69159. * Creates a new Database
  69160. * @param urlToScene defines the url to load the scene
  69161. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69162. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69163. */
  69164. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69165. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69166. var _this = this;
  69167. // Handling various flavors of prefixed version of IndexedDB
  69168. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69169. this.callbackManifestChecked = callbackManifestChecked;
  69170. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69171. this.db = null;
  69172. this._enableSceneOffline = false;
  69173. this._enableTexturesOffline = false;
  69174. this.manifestVersionFound = 0;
  69175. this.mustUpdateRessources = false;
  69176. this.hasReachedQuota = false;
  69177. if (!Database.IDBStorageEnabled) {
  69178. this.callbackManifestChecked(true);
  69179. }
  69180. else {
  69181. if (disableManifestCheck) {
  69182. this._enableSceneOffline = true;
  69183. this._enableTexturesOffline = true;
  69184. this.manifestVersionFound = 1;
  69185. BABYLON.Tools.SetImmediate(function () {
  69186. _this.callbackManifestChecked(true);
  69187. });
  69188. }
  69189. else {
  69190. this._checkManifestFile();
  69191. }
  69192. }
  69193. }
  69194. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69195. /**
  69196. * Gets a boolean indicating if scene must be saved in the database
  69197. */
  69198. get: function () {
  69199. return this._enableSceneOffline;
  69200. },
  69201. enumerable: true,
  69202. configurable: true
  69203. });
  69204. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69205. /**
  69206. * Gets a boolean indicating if textures must be saved in the database
  69207. */
  69208. get: function () {
  69209. return this._enableTexturesOffline;
  69210. },
  69211. enumerable: true,
  69212. configurable: true
  69213. });
  69214. Database.prototype._checkManifestFile = function () {
  69215. var _this = this;
  69216. var noManifestFile = function () {
  69217. _this._enableSceneOffline = false;
  69218. _this._enableTexturesOffline = false;
  69219. _this.callbackManifestChecked(false);
  69220. };
  69221. var timeStampUsed = false;
  69222. var manifestURL = this.currentSceneUrl + ".manifest";
  69223. var xhr = new XMLHttpRequest();
  69224. if (navigator.onLine) {
  69225. // Adding a timestamp to by-pass browsers' cache
  69226. timeStampUsed = true;
  69227. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69228. }
  69229. xhr.open("GET", manifestURL, true);
  69230. xhr.addEventListener("load", function () {
  69231. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69232. try {
  69233. var manifestFile = JSON.parse(xhr.response);
  69234. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69235. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69236. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69237. _this.manifestVersionFound = manifestFile.version;
  69238. }
  69239. if (_this.callbackManifestChecked) {
  69240. _this.callbackManifestChecked(true);
  69241. }
  69242. }
  69243. catch (ex) {
  69244. noManifestFile();
  69245. }
  69246. }
  69247. else {
  69248. noManifestFile();
  69249. }
  69250. }, false);
  69251. xhr.addEventListener("error", function (event) {
  69252. if (timeStampUsed) {
  69253. timeStampUsed = false;
  69254. // Let's retry without the timeStamp
  69255. // It could fail when coupled with HTML5 Offline API
  69256. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69257. xhr.open("GET", retryManifestURL, true);
  69258. xhr.send();
  69259. }
  69260. else {
  69261. noManifestFile();
  69262. }
  69263. }, false);
  69264. try {
  69265. xhr.send();
  69266. }
  69267. catch (ex) {
  69268. BABYLON.Tools.Error("Error on XHR send request.");
  69269. this.callbackManifestChecked(false);
  69270. }
  69271. };
  69272. /**
  69273. * Open the database and make it available
  69274. * @param successCallback defines the callback to call on success
  69275. * @param errorCallback defines the callback to call on error
  69276. */
  69277. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69278. var _this = this;
  69279. var handleError = function () {
  69280. _this.isSupported = false;
  69281. if (errorCallback)
  69282. errorCallback();
  69283. };
  69284. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69285. // Your browser doesn't support IndexedDB
  69286. this.isSupported = false;
  69287. if (errorCallback)
  69288. errorCallback();
  69289. }
  69290. else {
  69291. // If the DB hasn't been opened or created yet
  69292. if (!this.db) {
  69293. this.hasReachedQuota = false;
  69294. this.isSupported = true;
  69295. var request = this.idbFactory.open("babylonjs", 1);
  69296. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69297. request.onerror = function (event) {
  69298. handleError();
  69299. };
  69300. // executes when a version change transaction cannot complete due to other active transactions
  69301. request.onblocked = function (event) {
  69302. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69303. handleError();
  69304. };
  69305. // DB has been opened successfully
  69306. request.onsuccess = function (event) {
  69307. _this.db = request.result;
  69308. successCallback();
  69309. };
  69310. // Initialization of the DB. Creating Scenes & Textures stores
  69311. request.onupgradeneeded = function (event) {
  69312. _this.db = (event.target).result;
  69313. if (_this.db) {
  69314. try {
  69315. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69316. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69317. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69318. }
  69319. catch (ex) {
  69320. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69321. handleError();
  69322. }
  69323. }
  69324. };
  69325. }
  69326. // DB has already been created and opened
  69327. else {
  69328. if (successCallback)
  69329. successCallback();
  69330. }
  69331. }
  69332. };
  69333. /**
  69334. * Loads an image from the database
  69335. * @param url defines the url to load from
  69336. * @param image defines the target DOM image
  69337. */
  69338. Database.prototype.loadImageFromDB = function (url, image) {
  69339. var _this = this;
  69340. var completeURL = Database._ReturnFullUrlLocation(url);
  69341. var saveAndLoadImage = function () {
  69342. if (!_this.hasReachedQuota && _this.db !== null) {
  69343. // the texture is not yet in the DB, let's try to save it
  69344. _this._saveImageIntoDBAsync(completeURL, image);
  69345. }
  69346. // If the texture is not in the DB and we've reached the DB quota limit
  69347. // let's load it directly from the web
  69348. else {
  69349. image.src = url;
  69350. }
  69351. };
  69352. if (!this.mustUpdateRessources) {
  69353. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69354. }
  69355. // First time we're download the images or update requested in the manifest file by a version change
  69356. else {
  69357. saveAndLoadImage();
  69358. }
  69359. };
  69360. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69361. if (this.isSupported && this.db !== null) {
  69362. var texture;
  69363. var transaction = this.db.transaction(["textures"]);
  69364. transaction.onabort = function (event) {
  69365. image.src = url;
  69366. };
  69367. transaction.oncomplete = function (event) {
  69368. var blobTextureURL;
  69369. if (texture) {
  69370. var URL = window.URL || window.webkitURL;
  69371. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69372. image.onerror = function () {
  69373. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69374. image.src = url;
  69375. };
  69376. image.src = blobTextureURL;
  69377. }
  69378. else {
  69379. notInDBCallback();
  69380. }
  69381. };
  69382. var getRequest = transaction.objectStore("textures").get(url);
  69383. getRequest.onsuccess = function (event) {
  69384. texture = (event.target).result;
  69385. };
  69386. getRequest.onerror = function (event) {
  69387. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69388. image.src = url;
  69389. };
  69390. }
  69391. else {
  69392. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69393. image.src = url;
  69394. }
  69395. };
  69396. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69397. var _this = this;
  69398. if (this.isSupported) {
  69399. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69400. var generateBlobUrl = function () {
  69401. var blobTextureURL;
  69402. if (blob) {
  69403. var URL = window.URL || window.webkitURL;
  69404. try {
  69405. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69406. }
  69407. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69408. catch (ex) {
  69409. blobTextureURL = URL.createObjectURL(blob);
  69410. }
  69411. }
  69412. if (blobTextureURL) {
  69413. image.src = blobTextureURL;
  69414. }
  69415. };
  69416. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69417. var xhr = new XMLHttpRequest(), blob;
  69418. xhr.open("GET", url, true);
  69419. xhr.responseType = "blob";
  69420. xhr.addEventListener("load", function () {
  69421. if (xhr.status === 200 && _this.db) {
  69422. // Blob as response (XHR2)
  69423. blob = xhr.response;
  69424. var transaction = _this.db.transaction(["textures"], "readwrite");
  69425. // the transaction could abort because of a QuotaExceededError error
  69426. transaction.onabort = function (event) {
  69427. try {
  69428. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69429. var srcElement = (event.srcElement || event.target);
  69430. var error = srcElement.error;
  69431. if (error && error.name === "QuotaExceededError") {
  69432. _this.hasReachedQuota = true;
  69433. }
  69434. }
  69435. catch (ex) { }
  69436. generateBlobUrl();
  69437. };
  69438. transaction.oncomplete = function (event) {
  69439. generateBlobUrl();
  69440. };
  69441. var newTexture = { textureUrl: url, data: blob };
  69442. try {
  69443. // Put the blob into the dabase
  69444. var addRequest = transaction.objectStore("textures").put(newTexture);
  69445. addRequest.onsuccess = function (event) {
  69446. };
  69447. addRequest.onerror = function (event) {
  69448. generateBlobUrl();
  69449. };
  69450. }
  69451. catch (ex) {
  69452. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69453. if (ex.code === 25) {
  69454. Database.IsUASupportingBlobStorage = false;
  69455. }
  69456. image.src = url;
  69457. }
  69458. }
  69459. else {
  69460. image.src = url;
  69461. }
  69462. }, false);
  69463. xhr.addEventListener("error", function (event) {
  69464. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69465. image.src = url;
  69466. }, false);
  69467. xhr.send();
  69468. }
  69469. else {
  69470. image.src = url;
  69471. }
  69472. }
  69473. else {
  69474. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69475. image.src = url;
  69476. }
  69477. };
  69478. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69479. var _this = this;
  69480. var updateVersion = function () {
  69481. // the version is not yet in the DB or we need to update it
  69482. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69483. };
  69484. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69485. };
  69486. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69487. var _this = this;
  69488. if (this.isSupported && this.db) {
  69489. var version;
  69490. try {
  69491. var transaction = this.db.transaction(["versions"]);
  69492. transaction.oncomplete = function (event) {
  69493. if (version) {
  69494. // If the version in the JSON file is different from the version in DB
  69495. if (_this.manifestVersionFound !== version.data) {
  69496. _this.mustUpdateRessources = true;
  69497. updateInDBCallback();
  69498. }
  69499. else {
  69500. callback(version.data);
  69501. }
  69502. }
  69503. // version was not found in DB
  69504. else {
  69505. _this.mustUpdateRessources = true;
  69506. updateInDBCallback();
  69507. }
  69508. };
  69509. transaction.onabort = function (event) {
  69510. callback(-1);
  69511. };
  69512. var getRequest = transaction.objectStore("versions").get(url);
  69513. getRequest.onsuccess = function (event) {
  69514. version = (event.target).result;
  69515. };
  69516. getRequest.onerror = function (event) {
  69517. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69518. callback(-1);
  69519. };
  69520. }
  69521. catch (ex) {
  69522. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69523. callback(-1);
  69524. }
  69525. }
  69526. else {
  69527. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69528. callback(-1);
  69529. }
  69530. };
  69531. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69532. var _this = this;
  69533. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69534. try {
  69535. // Open a transaction to the database
  69536. var transaction = this.db.transaction(["versions"], "readwrite");
  69537. // the transaction could abort because of a QuotaExceededError error
  69538. transaction.onabort = function (event) {
  69539. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69540. var error = event.srcElement['error'];
  69541. if (error && error.name === "QuotaExceededError") {
  69542. _this.hasReachedQuota = true;
  69543. }
  69544. }
  69545. catch (ex) { }
  69546. callback(-1);
  69547. };
  69548. transaction.oncomplete = function (event) {
  69549. callback(_this.manifestVersionFound);
  69550. };
  69551. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69552. // Put the scene into the database
  69553. var addRequest = transaction.objectStore("versions").put(newVersion);
  69554. addRequest.onsuccess = function (event) {
  69555. };
  69556. addRequest.onerror = function (event) {
  69557. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69558. };
  69559. }
  69560. catch (ex) {
  69561. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69562. callback(-1);
  69563. }
  69564. }
  69565. else {
  69566. callback(-1);
  69567. }
  69568. };
  69569. /**
  69570. * Loads a file from database
  69571. * @param url defines the URL to load from
  69572. * @param sceneLoaded defines a callback to call on success
  69573. * @param progressCallBack defines a callback to call when progress changed
  69574. * @param errorCallback defines a callback to call on error
  69575. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69576. */
  69577. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69578. var _this = this;
  69579. var completeUrl = Database._ReturnFullUrlLocation(url);
  69580. var saveAndLoadFile = function () {
  69581. // the scene is not yet in the DB, let's try to save it
  69582. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69583. };
  69584. this._checkVersionFromDB(completeUrl, function (version) {
  69585. if (version !== -1) {
  69586. if (!_this.mustUpdateRessources) {
  69587. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69588. }
  69589. else {
  69590. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69591. }
  69592. }
  69593. else {
  69594. if (errorCallback) {
  69595. errorCallback();
  69596. }
  69597. }
  69598. });
  69599. };
  69600. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69601. if (this.isSupported && this.db) {
  69602. var targetStore;
  69603. if (url.indexOf(".babylon") !== -1) {
  69604. targetStore = "scenes";
  69605. }
  69606. else {
  69607. targetStore = "textures";
  69608. }
  69609. var file;
  69610. var transaction = this.db.transaction([targetStore]);
  69611. transaction.oncomplete = function (event) {
  69612. if (file) {
  69613. callback(file.data);
  69614. }
  69615. // file was not found in DB
  69616. else {
  69617. notInDBCallback();
  69618. }
  69619. };
  69620. transaction.onabort = function (event) {
  69621. notInDBCallback();
  69622. };
  69623. var getRequest = transaction.objectStore(targetStore).get(url);
  69624. getRequest.onsuccess = function (event) {
  69625. file = (event.target).result;
  69626. };
  69627. getRequest.onerror = function (event) {
  69628. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69629. notInDBCallback();
  69630. };
  69631. }
  69632. else {
  69633. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69634. callback();
  69635. }
  69636. };
  69637. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69638. var _this = this;
  69639. if (this.isSupported) {
  69640. var targetStore;
  69641. if (url.indexOf(".babylon") !== -1) {
  69642. targetStore = "scenes";
  69643. }
  69644. else {
  69645. targetStore = "textures";
  69646. }
  69647. // Create XHR
  69648. var xhr = new XMLHttpRequest();
  69649. var fileData;
  69650. xhr.open("GET", url, true);
  69651. if (useArrayBuffer) {
  69652. xhr.responseType = "arraybuffer";
  69653. }
  69654. if (progressCallback) {
  69655. xhr.onprogress = progressCallback;
  69656. }
  69657. xhr.addEventListener("load", function () {
  69658. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69659. // Blob as response (XHR2)
  69660. //fileData = xhr.responseText;
  69661. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69662. if (!_this.hasReachedQuota && _this.db) {
  69663. // Open a transaction to the database
  69664. var transaction = _this.db.transaction([targetStore], "readwrite");
  69665. // the transaction could abort because of a QuotaExceededError error
  69666. transaction.onabort = function (event) {
  69667. try {
  69668. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69669. var error = event.srcElement['error'];
  69670. if (error && error.name === "QuotaExceededError") {
  69671. _this.hasReachedQuota = true;
  69672. }
  69673. }
  69674. catch (ex) { }
  69675. callback(fileData);
  69676. };
  69677. transaction.oncomplete = function (event) {
  69678. callback(fileData);
  69679. };
  69680. var newFile;
  69681. if (targetStore === "scenes") {
  69682. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69683. }
  69684. else {
  69685. newFile = { textureUrl: url, data: fileData };
  69686. }
  69687. try {
  69688. // Put the scene into the database
  69689. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69690. addRequest.onsuccess = function (event) {
  69691. };
  69692. addRequest.onerror = function (event) {
  69693. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69694. };
  69695. }
  69696. catch (ex) {
  69697. callback(fileData);
  69698. }
  69699. }
  69700. else {
  69701. callback(fileData);
  69702. }
  69703. }
  69704. else {
  69705. callback();
  69706. }
  69707. }, false);
  69708. xhr.addEventListener("error", function (event) {
  69709. BABYLON.Tools.Error("error on XHR request.");
  69710. callback();
  69711. }, false);
  69712. xhr.send();
  69713. }
  69714. else {
  69715. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69716. callback();
  69717. }
  69718. };
  69719. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69720. Database.IsUASupportingBlobStorage = true;
  69721. /** Gets a boolean indicating if Database storate is enabled */
  69722. Database.IDBStorageEnabled = true;
  69723. Database._ParseURL = function (url) {
  69724. var a = document.createElement('a');
  69725. a.href = url;
  69726. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69727. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69728. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69729. return absLocation;
  69730. };
  69731. Database._ReturnFullUrlLocation = function (url) {
  69732. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69733. return (Database._ParseURL(window.location.href) + url);
  69734. }
  69735. else {
  69736. return url;
  69737. }
  69738. };
  69739. return Database;
  69740. }());
  69741. BABYLON.Database = Database;
  69742. })(BABYLON || (BABYLON = {}));
  69743. //# sourceMappingURL=babylon.database.js.map
  69744. var BABYLON;
  69745. (function (BABYLON) {
  69746. var FresnelParameters = /** @class */ (function () {
  69747. function FresnelParameters() {
  69748. this._isEnabled = true;
  69749. this.leftColor = BABYLON.Color3.White();
  69750. this.rightColor = BABYLON.Color3.Black();
  69751. this.bias = 0;
  69752. this.power = 1;
  69753. }
  69754. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69755. get: function () {
  69756. return this._isEnabled;
  69757. },
  69758. set: function (value) {
  69759. if (this._isEnabled === value) {
  69760. return;
  69761. }
  69762. this._isEnabled = value;
  69763. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69764. },
  69765. enumerable: true,
  69766. configurable: true
  69767. });
  69768. FresnelParameters.prototype.clone = function () {
  69769. var newFresnelParameters = new FresnelParameters();
  69770. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69771. return newFresnelParameters;
  69772. };
  69773. FresnelParameters.prototype.serialize = function () {
  69774. var serializationObject = {};
  69775. serializationObject.isEnabled = this.isEnabled;
  69776. serializationObject.leftColor = this.leftColor.asArray();
  69777. serializationObject.rightColor = this.rightColor.asArray();
  69778. serializationObject.bias = this.bias;
  69779. serializationObject.power = this.power;
  69780. return serializationObject;
  69781. };
  69782. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69783. var fresnelParameters = new FresnelParameters();
  69784. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69785. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69786. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69787. fresnelParameters.bias = parsedFresnelParameters.bias;
  69788. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69789. return fresnelParameters;
  69790. };
  69791. return FresnelParameters;
  69792. }());
  69793. BABYLON.FresnelParameters = FresnelParameters;
  69794. })(BABYLON || (BABYLON = {}));
  69795. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69796. var BABYLON;
  69797. (function (BABYLON) {
  69798. var MultiMaterial = /** @class */ (function (_super) {
  69799. __extends(MultiMaterial, _super);
  69800. function MultiMaterial(name, scene) {
  69801. var _this = _super.call(this, name, scene, true) || this;
  69802. scene.multiMaterials.push(_this);
  69803. _this.subMaterials = new Array();
  69804. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69805. return _this;
  69806. }
  69807. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69808. get: function () {
  69809. return this._subMaterials;
  69810. },
  69811. set: function (value) {
  69812. this._subMaterials = value;
  69813. this._hookArray(value);
  69814. },
  69815. enumerable: true,
  69816. configurable: true
  69817. });
  69818. MultiMaterial.prototype._hookArray = function (array) {
  69819. var _this = this;
  69820. var oldPush = array.push;
  69821. array.push = function () {
  69822. var items = [];
  69823. for (var _i = 0; _i < arguments.length; _i++) {
  69824. items[_i] = arguments[_i];
  69825. }
  69826. var result = oldPush.apply(array, items);
  69827. _this._markAllSubMeshesAsTexturesDirty();
  69828. return result;
  69829. };
  69830. var oldSplice = array.splice;
  69831. array.splice = function (index, deleteCount) {
  69832. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69833. _this._markAllSubMeshesAsTexturesDirty();
  69834. return deleted;
  69835. };
  69836. };
  69837. // Properties
  69838. MultiMaterial.prototype.getSubMaterial = function (index) {
  69839. if (index < 0 || index >= this.subMaterials.length) {
  69840. return this.getScene().defaultMaterial;
  69841. }
  69842. return this.subMaterials[index];
  69843. };
  69844. MultiMaterial.prototype.getActiveTextures = function () {
  69845. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69846. if (subMaterial) {
  69847. return subMaterial.getActiveTextures();
  69848. }
  69849. else {
  69850. return [];
  69851. }
  69852. }));
  69853. var _a;
  69854. };
  69855. // Methods
  69856. MultiMaterial.prototype.getClassName = function () {
  69857. return "MultiMaterial";
  69858. };
  69859. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69860. for (var index = 0; index < this.subMaterials.length; index++) {
  69861. var subMaterial = this.subMaterials[index];
  69862. if (subMaterial) {
  69863. if (subMaterial.storeEffectOnSubMeshes) {
  69864. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69865. return false;
  69866. }
  69867. continue;
  69868. }
  69869. if (!subMaterial.isReady(mesh)) {
  69870. return false;
  69871. }
  69872. }
  69873. }
  69874. return true;
  69875. };
  69876. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69877. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69878. for (var index = 0; index < this.subMaterials.length; index++) {
  69879. var subMaterial = null;
  69880. var current = this.subMaterials[index];
  69881. if (cloneChildren && current) {
  69882. subMaterial = current.clone(name + "-" + current.name);
  69883. }
  69884. else {
  69885. subMaterial = this.subMaterials[index];
  69886. }
  69887. newMultiMaterial.subMaterials.push(subMaterial);
  69888. }
  69889. return newMultiMaterial;
  69890. };
  69891. MultiMaterial.prototype.serialize = function () {
  69892. var serializationObject = {};
  69893. serializationObject.name = this.name;
  69894. serializationObject.id = this.id;
  69895. if (BABYLON.Tags) {
  69896. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69897. }
  69898. serializationObject.materials = [];
  69899. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69900. var subMat = this.subMaterials[matIndex];
  69901. if (subMat) {
  69902. serializationObject.materials.push(subMat.id);
  69903. }
  69904. else {
  69905. serializationObject.materials.push(null);
  69906. }
  69907. }
  69908. return serializationObject;
  69909. };
  69910. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69911. var scene = this.getScene();
  69912. if (!scene) {
  69913. return;
  69914. }
  69915. var index = scene.multiMaterials.indexOf(this);
  69916. if (index >= 0) {
  69917. scene.multiMaterials.splice(index, 1);
  69918. }
  69919. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69920. };
  69921. return MultiMaterial;
  69922. }(BABYLON.Material));
  69923. BABYLON.MultiMaterial = MultiMaterial;
  69924. })(BABYLON || (BABYLON = {}));
  69925. //# sourceMappingURL=babylon.multiMaterial.js.map
  69926. var BABYLON;
  69927. (function (BABYLON) {
  69928. var FreeCameraTouchInput = /** @class */ (function () {
  69929. function FreeCameraTouchInput() {
  69930. this._offsetX = null;
  69931. this._offsetY = null;
  69932. this._pointerPressed = new Array();
  69933. this.touchAngularSensibility = 200000.0;
  69934. this.touchMoveSensibility = 250.0;
  69935. }
  69936. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69937. var _this = this;
  69938. var previousPosition = null;
  69939. if (this._pointerInput === undefined) {
  69940. this._onLostFocus = function (evt) {
  69941. _this._offsetX = null;
  69942. _this._offsetY = null;
  69943. };
  69944. this._pointerInput = function (p, s) {
  69945. var evt = p.event;
  69946. if (evt.pointerType === "mouse") {
  69947. return;
  69948. }
  69949. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69950. if (!noPreventDefault) {
  69951. evt.preventDefault();
  69952. }
  69953. _this._pointerPressed.push(evt.pointerId);
  69954. if (_this._pointerPressed.length !== 1) {
  69955. return;
  69956. }
  69957. previousPosition = {
  69958. x: evt.clientX,
  69959. y: evt.clientY
  69960. };
  69961. }
  69962. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69963. if (!noPreventDefault) {
  69964. evt.preventDefault();
  69965. }
  69966. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69967. if (index === -1) {
  69968. return;
  69969. }
  69970. _this._pointerPressed.splice(index, 1);
  69971. if (index != 0) {
  69972. return;
  69973. }
  69974. previousPosition = null;
  69975. _this._offsetX = null;
  69976. _this._offsetY = null;
  69977. }
  69978. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69979. if (!noPreventDefault) {
  69980. evt.preventDefault();
  69981. }
  69982. if (!previousPosition) {
  69983. return;
  69984. }
  69985. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69986. if (index != 0) {
  69987. return;
  69988. }
  69989. _this._offsetX = evt.clientX - previousPosition.x;
  69990. _this._offsetY = -(evt.clientY - previousPosition.y);
  69991. }
  69992. };
  69993. }
  69994. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69995. if (this._onLostFocus) {
  69996. element.addEventListener("blur", this._onLostFocus);
  69997. }
  69998. };
  69999. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70000. if (this._pointerInput && element) {
  70001. if (this._observer) {
  70002. this.camera.getScene().onPointerObservable.remove(this._observer);
  70003. this._observer = null;
  70004. }
  70005. if (this._onLostFocus) {
  70006. element.removeEventListener("blur", this._onLostFocus);
  70007. this._onLostFocus = null;
  70008. }
  70009. this._pointerPressed = [];
  70010. this._offsetX = null;
  70011. this._offsetY = null;
  70012. }
  70013. };
  70014. FreeCameraTouchInput.prototype.checkInputs = function () {
  70015. if (this._offsetX && this._offsetY) {
  70016. var camera = this.camera;
  70017. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70018. if (this._pointerPressed.length > 1) {
  70019. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70020. }
  70021. else {
  70022. var speed = camera._computeLocalCameraSpeed();
  70023. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70024. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70025. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70026. }
  70027. }
  70028. };
  70029. FreeCameraTouchInput.prototype.getClassName = function () {
  70030. return "FreeCameraTouchInput";
  70031. };
  70032. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70033. return "touch";
  70034. };
  70035. __decorate([
  70036. BABYLON.serialize()
  70037. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70038. __decorate([
  70039. BABYLON.serialize()
  70040. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70041. return FreeCameraTouchInput;
  70042. }());
  70043. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70044. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70045. })(BABYLON || (BABYLON = {}));
  70046. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70047. var BABYLON;
  70048. (function (BABYLON) {
  70049. // We're mainly based on the logic defined into the FreeCamera code
  70050. var TouchCamera = /** @class */ (function (_super) {
  70051. __extends(TouchCamera, _super);
  70052. //-- end properties for backward compatibility for inputs
  70053. function TouchCamera(name, position, scene) {
  70054. var _this = _super.call(this, name, position, scene) || this;
  70055. _this.inputs.addTouch();
  70056. _this._setupInputs();
  70057. return _this;
  70058. }
  70059. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70060. //-- Begin properties for backward compatibility for inputs
  70061. get: function () {
  70062. var touch = this.inputs.attached["touch"];
  70063. if (touch)
  70064. return touch.touchAngularSensibility;
  70065. return 0;
  70066. },
  70067. set: function (value) {
  70068. var touch = this.inputs.attached["touch"];
  70069. if (touch)
  70070. touch.touchAngularSensibility = value;
  70071. },
  70072. enumerable: true,
  70073. configurable: true
  70074. });
  70075. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70076. get: function () {
  70077. var touch = this.inputs.attached["touch"];
  70078. if (touch)
  70079. return touch.touchMoveSensibility;
  70080. return 0;
  70081. },
  70082. set: function (value) {
  70083. var touch = this.inputs.attached["touch"];
  70084. if (touch)
  70085. touch.touchMoveSensibility = value;
  70086. },
  70087. enumerable: true,
  70088. configurable: true
  70089. });
  70090. TouchCamera.prototype.getClassName = function () {
  70091. return "TouchCamera";
  70092. };
  70093. TouchCamera.prototype._setupInputs = function () {
  70094. var mouse = this.inputs.attached["mouse"];
  70095. if (mouse) {
  70096. mouse.touchEnabled = false;
  70097. }
  70098. };
  70099. return TouchCamera;
  70100. }(BABYLON.FreeCamera));
  70101. BABYLON.TouchCamera = TouchCamera;
  70102. })(BABYLON || (BABYLON = {}));
  70103. //# sourceMappingURL=babylon.touchCamera.js.map
  70104. var BABYLON;
  70105. (function (BABYLON) {
  70106. var ProceduralTexture = /** @class */ (function (_super) {
  70107. __extends(ProceduralTexture, _super);
  70108. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70109. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70110. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70111. if (isCube === void 0) { isCube = false; }
  70112. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70113. _this.isCube = isCube;
  70114. _this.isEnabled = true;
  70115. _this._currentRefreshId = -1;
  70116. _this._refreshRate = 1;
  70117. _this._vertexBuffers = {};
  70118. _this._uniforms = new Array();
  70119. _this._samplers = new Array();
  70120. _this._textures = {};
  70121. _this._floats = {};
  70122. _this._floatsArrays = {};
  70123. _this._colors3 = {};
  70124. _this._colors4 = {};
  70125. _this._vectors2 = {};
  70126. _this._vectors3 = {};
  70127. _this._matrices = {};
  70128. _this._fallbackTextureUsed = false;
  70129. scene.proceduralTextures.push(_this);
  70130. _this._engine = scene.getEngine();
  70131. _this.name = name;
  70132. _this.isRenderTarget = true;
  70133. _this._size = size;
  70134. _this._generateMipMaps = generateMipMaps;
  70135. _this.setFragment(fragment);
  70136. _this._fallbackTexture = fallbackTexture;
  70137. if (isCube) {
  70138. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70139. _this.setFloat("face", 0);
  70140. }
  70141. else {
  70142. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70143. }
  70144. // VBO
  70145. var vertices = [];
  70146. vertices.push(1, 1);
  70147. vertices.push(-1, 1);
  70148. vertices.push(-1, -1);
  70149. vertices.push(1, -1);
  70150. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70151. _this._createIndexBuffer();
  70152. return _this;
  70153. }
  70154. ProceduralTexture.prototype._createIndexBuffer = function () {
  70155. var engine = this._engine;
  70156. // Indices
  70157. var indices = [];
  70158. indices.push(0);
  70159. indices.push(1);
  70160. indices.push(2);
  70161. indices.push(0);
  70162. indices.push(2);
  70163. indices.push(3);
  70164. this._indexBuffer = engine.createIndexBuffer(indices);
  70165. };
  70166. ProceduralTexture.prototype._rebuild = function () {
  70167. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70168. if (vb) {
  70169. vb._rebuild();
  70170. }
  70171. this._createIndexBuffer();
  70172. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70173. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70174. }
  70175. };
  70176. ProceduralTexture.prototype.reset = function () {
  70177. if (this._effect === undefined) {
  70178. return;
  70179. }
  70180. var engine = this._engine;
  70181. engine._releaseEffect(this._effect);
  70182. };
  70183. ProceduralTexture.prototype.isReady = function () {
  70184. var _this = this;
  70185. var engine = this._engine;
  70186. var shaders;
  70187. if (!this._fragment) {
  70188. return false;
  70189. }
  70190. if (this._fallbackTextureUsed) {
  70191. return true;
  70192. }
  70193. if (this._fragment.fragmentElement !== undefined) {
  70194. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70195. }
  70196. else {
  70197. shaders = { vertex: "procedural", fragment: this._fragment };
  70198. }
  70199. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70200. _this.releaseInternalTexture();
  70201. if (_this._fallbackTexture) {
  70202. _this._texture = _this._fallbackTexture._texture;
  70203. if (_this._texture) {
  70204. _this._texture.incrementReferences();
  70205. }
  70206. }
  70207. _this._fallbackTextureUsed = true;
  70208. });
  70209. return this._effect.isReady();
  70210. };
  70211. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70212. this._currentRefreshId = -1;
  70213. };
  70214. ProceduralTexture.prototype.setFragment = function (fragment) {
  70215. this._fragment = fragment;
  70216. };
  70217. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70218. get: function () {
  70219. return this._refreshRate;
  70220. },
  70221. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70222. set: function (value) {
  70223. this._refreshRate = value;
  70224. this.resetRefreshCounter();
  70225. },
  70226. enumerable: true,
  70227. configurable: true
  70228. });
  70229. ProceduralTexture.prototype._shouldRender = function () {
  70230. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70231. return false;
  70232. }
  70233. if (this._fallbackTextureUsed) {
  70234. return false;
  70235. }
  70236. if (this._currentRefreshId === -1) { // At least render once
  70237. this._currentRefreshId = 1;
  70238. return true;
  70239. }
  70240. if (this.refreshRate === this._currentRefreshId) {
  70241. this._currentRefreshId = 1;
  70242. return true;
  70243. }
  70244. this._currentRefreshId++;
  70245. return false;
  70246. };
  70247. ProceduralTexture.prototype.getRenderSize = function () {
  70248. return this._size;
  70249. };
  70250. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70251. if (this._fallbackTextureUsed) {
  70252. return;
  70253. }
  70254. this.releaseInternalTexture();
  70255. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70256. };
  70257. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70258. if (this._uniforms.indexOf(uniformName) === -1) {
  70259. this._uniforms.push(uniformName);
  70260. }
  70261. };
  70262. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70263. if (this._samplers.indexOf(name) === -1) {
  70264. this._samplers.push(name);
  70265. }
  70266. this._textures[name] = texture;
  70267. return this;
  70268. };
  70269. ProceduralTexture.prototype.setFloat = function (name, value) {
  70270. this._checkUniform(name);
  70271. this._floats[name] = value;
  70272. return this;
  70273. };
  70274. ProceduralTexture.prototype.setFloats = function (name, value) {
  70275. this._checkUniform(name);
  70276. this._floatsArrays[name] = value;
  70277. return this;
  70278. };
  70279. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70280. this._checkUniform(name);
  70281. this._colors3[name] = value;
  70282. return this;
  70283. };
  70284. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70285. this._checkUniform(name);
  70286. this._colors4[name] = value;
  70287. return this;
  70288. };
  70289. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70290. this._checkUniform(name);
  70291. this._vectors2[name] = value;
  70292. return this;
  70293. };
  70294. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70295. this._checkUniform(name);
  70296. this._vectors3[name] = value;
  70297. return this;
  70298. };
  70299. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70300. this._checkUniform(name);
  70301. this._matrices[name] = value;
  70302. return this;
  70303. };
  70304. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70305. var scene = this.getScene();
  70306. if (!scene) {
  70307. return;
  70308. }
  70309. var engine = this._engine;
  70310. // Render
  70311. engine.enableEffect(this._effect);
  70312. engine.setState(false);
  70313. // Texture
  70314. for (var name in this._textures) {
  70315. this._effect.setTexture(name, this._textures[name]);
  70316. }
  70317. // Float
  70318. for (name in this._floats) {
  70319. this._effect.setFloat(name, this._floats[name]);
  70320. }
  70321. // Floats
  70322. for (name in this._floatsArrays) {
  70323. this._effect.setArray(name, this._floatsArrays[name]);
  70324. }
  70325. // Color3
  70326. for (name in this._colors3) {
  70327. this._effect.setColor3(name, this._colors3[name]);
  70328. }
  70329. // Color4
  70330. for (name in this._colors4) {
  70331. var color = this._colors4[name];
  70332. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70333. }
  70334. // Vector2
  70335. for (name in this._vectors2) {
  70336. this._effect.setVector2(name, this._vectors2[name]);
  70337. }
  70338. // Vector3
  70339. for (name in this._vectors3) {
  70340. this._effect.setVector3(name, this._vectors3[name]);
  70341. }
  70342. // Matrix
  70343. for (name in this._matrices) {
  70344. this._effect.setMatrix(name, this._matrices[name]);
  70345. }
  70346. if (!this._texture) {
  70347. return;
  70348. }
  70349. if (this.isCube) {
  70350. for (var face = 0; face < 6; face++) {
  70351. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70352. // VBOs
  70353. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70354. this._effect.setFloat("face", face);
  70355. // Clear
  70356. engine.clear(scene.clearColor, true, true, true);
  70357. // Draw order
  70358. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70359. // Mipmaps
  70360. if (face === 5) {
  70361. engine.generateMipMapsForCubemap(this._texture);
  70362. }
  70363. }
  70364. }
  70365. else {
  70366. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70367. // VBOs
  70368. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70369. // Clear
  70370. engine.clear(scene.clearColor, true, true, true);
  70371. // Draw order
  70372. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70373. }
  70374. // Unbind
  70375. engine.unBindFramebuffer(this._texture, this.isCube);
  70376. if (this.onGenerated) {
  70377. this.onGenerated();
  70378. }
  70379. };
  70380. ProceduralTexture.prototype.clone = function () {
  70381. var textureSize = this.getSize();
  70382. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70383. // Base texture
  70384. newTexture.hasAlpha = this.hasAlpha;
  70385. newTexture.level = this.level;
  70386. // RenderTarget Texture
  70387. newTexture.coordinatesMode = this.coordinatesMode;
  70388. return newTexture;
  70389. };
  70390. ProceduralTexture.prototype.dispose = function () {
  70391. var scene = this.getScene();
  70392. if (!scene) {
  70393. return;
  70394. }
  70395. var index = scene.proceduralTextures.indexOf(this);
  70396. if (index >= 0) {
  70397. scene.proceduralTextures.splice(index, 1);
  70398. }
  70399. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70400. if (vertexBuffer) {
  70401. vertexBuffer.dispose();
  70402. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70403. }
  70404. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70405. this._indexBuffer = null;
  70406. }
  70407. _super.prototype.dispose.call(this);
  70408. };
  70409. return ProceduralTexture;
  70410. }(BABYLON.Texture));
  70411. BABYLON.ProceduralTexture = ProceduralTexture;
  70412. })(BABYLON || (BABYLON = {}));
  70413. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70414. var BABYLON;
  70415. (function (BABYLON) {
  70416. var CustomProceduralTexture = /** @class */ (function (_super) {
  70417. __extends(CustomProceduralTexture, _super);
  70418. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70419. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70420. _this._animate = true;
  70421. _this._time = 0;
  70422. _this._texturePath = texturePath;
  70423. //Try to load json
  70424. _this.loadJson(texturePath);
  70425. _this.refreshRate = 1;
  70426. return _this;
  70427. }
  70428. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70429. var _this = this;
  70430. var noConfigFile = function () {
  70431. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70432. try {
  70433. _this.setFragment(_this._texturePath);
  70434. }
  70435. catch (ex) {
  70436. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70437. }
  70438. };
  70439. var configFileUrl = jsonUrl + "/config.json";
  70440. var xhr = new XMLHttpRequest();
  70441. xhr.open("GET", configFileUrl, true);
  70442. xhr.addEventListener("load", function () {
  70443. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70444. try {
  70445. _this._config = JSON.parse(xhr.response);
  70446. _this.updateShaderUniforms();
  70447. _this.updateTextures();
  70448. _this.setFragment(_this._texturePath + "/custom");
  70449. _this._animate = _this._config.animate;
  70450. _this.refreshRate = _this._config.refreshrate;
  70451. }
  70452. catch (ex) {
  70453. noConfigFile();
  70454. }
  70455. }
  70456. else {
  70457. noConfigFile();
  70458. }
  70459. }, false);
  70460. xhr.addEventListener("error", function () {
  70461. noConfigFile();
  70462. }, false);
  70463. try {
  70464. xhr.send();
  70465. }
  70466. catch (ex) {
  70467. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70468. }
  70469. };
  70470. CustomProceduralTexture.prototype.isReady = function () {
  70471. if (!_super.prototype.isReady.call(this)) {
  70472. return false;
  70473. }
  70474. for (var name in this._textures) {
  70475. var texture = this._textures[name];
  70476. if (!texture.isReady()) {
  70477. return false;
  70478. }
  70479. }
  70480. return true;
  70481. };
  70482. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70483. var scene = this.getScene();
  70484. if (this._animate && scene) {
  70485. this._time += scene.getAnimationRatio() * 0.03;
  70486. this.updateShaderUniforms();
  70487. }
  70488. _super.prototype.render.call(this, useCameraPostProcess);
  70489. };
  70490. CustomProceduralTexture.prototype.updateTextures = function () {
  70491. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70492. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70493. }
  70494. };
  70495. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70496. if (this._config) {
  70497. for (var j = 0; j < this._config.uniforms.length; j++) {
  70498. var uniform = this._config.uniforms[j];
  70499. switch (uniform.type) {
  70500. case "float":
  70501. this.setFloat(uniform.name, uniform.value);
  70502. break;
  70503. case "color3":
  70504. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70505. break;
  70506. case "color4":
  70507. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70508. break;
  70509. case "vector2":
  70510. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70511. break;
  70512. case "vector3":
  70513. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70514. break;
  70515. }
  70516. }
  70517. }
  70518. this.setFloat("time", this._time);
  70519. };
  70520. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70521. get: function () {
  70522. return this._animate;
  70523. },
  70524. set: function (value) {
  70525. this._animate = value;
  70526. },
  70527. enumerable: true,
  70528. configurable: true
  70529. });
  70530. return CustomProceduralTexture;
  70531. }(BABYLON.ProceduralTexture));
  70532. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70533. })(BABYLON || (BABYLON = {}));
  70534. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70535. var BABYLON;
  70536. (function (BABYLON) {
  70537. var FreeCameraGamepadInput = /** @class */ (function () {
  70538. function FreeCameraGamepadInput() {
  70539. this.gamepadAngularSensibility = 200;
  70540. this.gamepadMoveSensibility = 40;
  70541. // private members
  70542. this._cameraTransform = BABYLON.Matrix.Identity();
  70543. this._deltaTransform = BABYLON.Vector3.Zero();
  70544. this._vector3 = BABYLON.Vector3.Zero();
  70545. this._vector2 = BABYLON.Vector2.Zero();
  70546. }
  70547. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70548. var _this = this;
  70549. var manager = this.camera.getScene().gamepadManager;
  70550. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70551. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70552. // prioritize XBOX gamepads.
  70553. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70554. _this.gamepad = gamepad;
  70555. }
  70556. }
  70557. });
  70558. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70559. if (_this.gamepad === gamepad) {
  70560. _this.gamepad = null;
  70561. }
  70562. });
  70563. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70564. };
  70565. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70566. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70567. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70568. this.gamepad = null;
  70569. };
  70570. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70571. if (this.gamepad && this.gamepad.leftStick) {
  70572. var camera = this.camera;
  70573. var LSValues = this.gamepad.leftStick;
  70574. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70575. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70576. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70577. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70578. var RSValues = this.gamepad.rightStick;
  70579. if (RSValues) {
  70580. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70581. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70582. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70583. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70584. }
  70585. else {
  70586. RSValues = { x: 0, y: 0 };
  70587. }
  70588. if (!camera.rotationQuaternion) {
  70589. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70590. }
  70591. else {
  70592. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70593. }
  70594. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70595. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70596. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70597. camera.cameraDirection.addInPlace(this._deltaTransform);
  70598. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70599. camera.cameraRotation.addInPlace(this._vector2);
  70600. }
  70601. };
  70602. FreeCameraGamepadInput.prototype.getClassName = function () {
  70603. return "FreeCameraGamepadInput";
  70604. };
  70605. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70606. return "gamepad";
  70607. };
  70608. __decorate([
  70609. BABYLON.serialize()
  70610. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70611. __decorate([
  70612. BABYLON.serialize()
  70613. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70614. return FreeCameraGamepadInput;
  70615. }());
  70616. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70617. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70618. })(BABYLON || (BABYLON = {}));
  70619. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70620. var BABYLON;
  70621. (function (BABYLON) {
  70622. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70623. function ArcRotateCameraGamepadInput() {
  70624. this.gamepadRotationSensibility = 80;
  70625. this.gamepadMoveSensibility = 40;
  70626. }
  70627. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70628. var _this = this;
  70629. var manager = this.camera.getScene().gamepadManager;
  70630. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70631. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70632. // prioritize XBOX gamepads.
  70633. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70634. _this.gamepad = gamepad;
  70635. }
  70636. }
  70637. });
  70638. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70639. if (_this.gamepad === gamepad) {
  70640. _this.gamepad = null;
  70641. }
  70642. });
  70643. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70644. };
  70645. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70646. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70647. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70648. this.gamepad = null;
  70649. };
  70650. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70651. if (this.gamepad) {
  70652. var camera = this.camera;
  70653. var RSValues = this.gamepad.rightStick;
  70654. if (RSValues) {
  70655. if (RSValues.x != 0) {
  70656. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70657. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70658. camera.inertialAlphaOffset += normalizedRX;
  70659. }
  70660. }
  70661. if (RSValues.y != 0) {
  70662. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70663. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70664. camera.inertialBetaOffset += normalizedRY;
  70665. }
  70666. }
  70667. }
  70668. var LSValues = this.gamepad.leftStick;
  70669. if (LSValues && LSValues.y != 0) {
  70670. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70671. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70672. this.camera.inertialRadiusOffset -= normalizedLY;
  70673. }
  70674. }
  70675. }
  70676. };
  70677. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70678. return "ArcRotateCameraGamepadInput";
  70679. };
  70680. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70681. return "gamepad";
  70682. };
  70683. __decorate([
  70684. BABYLON.serialize()
  70685. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70686. __decorate([
  70687. BABYLON.serialize()
  70688. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70689. return ArcRotateCameraGamepadInput;
  70690. }());
  70691. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70692. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70693. })(BABYLON || (BABYLON = {}));
  70694. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70695. var BABYLON;
  70696. (function (BABYLON) {
  70697. var GamepadManager = /** @class */ (function () {
  70698. function GamepadManager(_scene) {
  70699. var _this = this;
  70700. this._scene = _scene;
  70701. this._babylonGamepads = [];
  70702. this._oneGamepadConnected = false;
  70703. this._isMonitoring = false;
  70704. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70705. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70706. this._gamepadEventSupported = false;
  70707. }
  70708. else {
  70709. this._gamepadEventSupported = 'GamepadEvent' in window;
  70710. this._gamepadSupport = (navigator.getGamepads ||
  70711. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70712. }
  70713. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70714. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70715. for (var i in _this._babylonGamepads) {
  70716. var gamepad = _this._babylonGamepads[i];
  70717. if (gamepad && gamepad._isConnected) {
  70718. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70719. }
  70720. }
  70721. });
  70722. this._onGamepadConnectedEvent = function (evt) {
  70723. var gamepad = evt.gamepad;
  70724. if (gamepad.index in _this._babylonGamepads) {
  70725. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70726. return;
  70727. }
  70728. }
  70729. var newGamepad;
  70730. if (_this._babylonGamepads[gamepad.index]) {
  70731. newGamepad = _this._babylonGamepads[gamepad.index];
  70732. newGamepad.browserGamepad = gamepad;
  70733. newGamepad._isConnected = true;
  70734. }
  70735. else {
  70736. newGamepad = _this._addNewGamepad(gamepad);
  70737. }
  70738. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70739. _this._startMonitoringGamepads();
  70740. };
  70741. this._onGamepadDisconnectedEvent = function (evt) {
  70742. var gamepad = evt.gamepad;
  70743. // Remove the gamepad from the list of gamepads to monitor.
  70744. for (var i in _this._babylonGamepads) {
  70745. if (_this._babylonGamepads[i].index === gamepad.index) {
  70746. var disconnectedGamepad = _this._babylonGamepads[i];
  70747. disconnectedGamepad._isConnected = false;
  70748. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70749. break;
  70750. }
  70751. }
  70752. };
  70753. if (this._gamepadSupport) {
  70754. //first add already-connected gamepads
  70755. this._updateGamepadObjects();
  70756. if (this._babylonGamepads.length) {
  70757. this._startMonitoringGamepads();
  70758. }
  70759. // Checking if the gamepad connected event is supported (like in Firefox)
  70760. if (this._gamepadEventSupported) {
  70761. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70762. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70763. }
  70764. else {
  70765. this._startMonitoringGamepads();
  70766. }
  70767. }
  70768. }
  70769. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70770. get: function () {
  70771. return this._babylonGamepads;
  70772. },
  70773. enumerable: true,
  70774. configurable: true
  70775. });
  70776. GamepadManager.prototype.getGamepadByType = function (type) {
  70777. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70778. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70779. var gamepad = _a[_i];
  70780. if (gamepad && gamepad.type === type) {
  70781. return gamepad;
  70782. }
  70783. }
  70784. return null;
  70785. };
  70786. GamepadManager.prototype.dispose = function () {
  70787. if (this._gamepadEventSupported) {
  70788. if (this._onGamepadConnectedEvent) {
  70789. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70790. }
  70791. if (this._onGamepadDisconnectedEvent) {
  70792. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70793. }
  70794. this._onGamepadConnectedEvent = null;
  70795. this._onGamepadDisconnectedEvent = null;
  70796. }
  70797. this._babylonGamepads.forEach(function (gamepad) {
  70798. gamepad.dispose();
  70799. });
  70800. this.onGamepadConnectedObservable.clear();
  70801. this.onGamepadDisconnectedObservable.clear();
  70802. this._oneGamepadConnected = false;
  70803. this._stopMonitoringGamepads();
  70804. this._babylonGamepads = [];
  70805. };
  70806. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70807. if (!this._oneGamepadConnected) {
  70808. this._oneGamepadConnected = true;
  70809. }
  70810. var newGamepad;
  70811. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70812. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70813. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70814. }
  70815. // if pose is supported, use the (WebVR) pose enabled controller
  70816. else if (gamepad.pose) {
  70817. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70818. }
  70819. else {
  70820. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70821. }
  70822. this._babylonGamepads[newGamepad.index] = newGamepad;
  70823. return newGamepad;
  70824. };
  70825. GamepadManager.prototype._startMonitoringGamepads = function () {
  70826. if (!this._isMonitoring) {
  70827. this._isMonitoring = true;
  70828. //back-comp
  70829. if (!this._scene) {
  70830. this._checkGamepadsStatus();
  70831. }
  70832. }
  70833. };
  70834. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70835. this._isMonitoring = false;
  70836. };
  70837. GamepadManager.prototype._checkGamepadsStatus = function () {
  70838. var _this = this;
  70839. // Hack to be compatible Chrome
  70840. this._updateGamepadObjects();
  70841. for (var i in this._babylonGamepads) {
  70842. var gamepad = this._babylonGamepads[i];
  70843. if (!gamepad || !gamepad.isConnected) {
  70844. continue;
  70845. }
  70846. gamepad.update();
  70847. }
  70848. if (this._isMonitoring && !this._scene) {
  70849. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70850. }
  70851. };
  70852. // This function is called only on Chrome, which does not properly support
  70853. // connection/disconnection events and forces you to recopy again the gamepad object
  70854. GamepadManager.prototype._updateGamepadObjects = function () {
  70855. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70856. for (var i = 0; i < gamepads.length; i++) {
  70857. var gamepad = gamepads[i];
  70858. if (gamepad) {
  70859. if (!this._babylonGamepads[gamepad.index]) {
  70860. var newGamepad = this._addNewGamepad(gamepad);
  70861. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70862. }
  70863. else {
  70864. // Forced to copy again this object for Chrome for unknown reason
  70865. this._babylonGamepads[i].browserGamepad = gamepad;
  70866. if (!this._babylonGamepads[i].isConnected) {
  70867. this._babylonGamepads[i]._isConnected = true;
  70868. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70869. }
  70870. }
  70871. }
  70872. }
  70873. };
  70874. return GamepadManager;
  70875. }());
  70876. BABYLON.GamepadManager = GamepadManager;
  70877. })(BABYLON || (BABYLON = {}));
  70878. //# sourceMappingURL=babylon.gamepadManager.js.map
  70879. var BABYLON;
  70880. (function (BABYLON) {
  70881. var StickValues = /** @class */ (function () {
  70882. function StickValues(x, y) {
  70883. this.x = x;
  70884. this.y = y;
  70885. }
  70886. return StickValues;
  70887. }());
  70888. BABYLON.StickValues = StickValues;
  70889. var Gamepad = /** @class */ (function () {
  70890. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70891. if (leftStickX === void 0) { leftStickX = 0; }
  70892. if (leftStickY === void 0) { leftStickY = 1; }
  70893. if (rightStickX === void 0) { rightStickX = 2; }
  70894. if (rightStickY === void 0) { rightStickY = 3; }
  70895. this.id = id;
  70896. this.index = index;
  70897. this.browserGamepad = browserGamepad;
  70898. this._isConnected = true;
  70899. this._invertLeftStickY = false;
  70900. this.type = Gamepad.GAMEPAD;
  70901. this._leftStickAxisX = leftStickX;
  70902. this._leftStickAxisY = leftStickY;
  70903. this._rightStickAxisX = rightStickX;
  70904. this._rightStickAxisY = rightStickY;
  70905. if (this.browserGamepad.axes.length >= 2) {
  70906. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70907. }
  70908. if (this.browserGamepad.axes.length >= 4) {
  70909. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70910. }
  70911. }
  70912. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70913. get: function () {
  70914. return this._isConnected;
  70915. },
  70916. enumerable: true,
  70917. configurable: true
  70918. });
  70919. Gamepad.prototype.onleftstickchanged = function (callback) {
  70920. this._onleftstickchanged = callback;
  70921. };
  70922. Gamepad.prototype.onrightstickchanged = function (callback) {
  70923. this._onrightstickchanged = callback;
  70924. };
  70925. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70926. get: function () {
  70927. return this._leftStick;
  70928. },
  70929. set: function (newValues) {
  70930. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70931. this._onleftstickchanged(newValues);
  70932. }
  70933. this._leftStick = newValues;
  70934. },
  70935. enumerable: true,
  70936. configurable: true
  70937. });
  70938. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70939. get: function () {
  70940. return this._rightStick;
  70941. },
  70942. set: function (newValues) {
  70943. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70944. this._onrightstickchanged(newValues);
  70945. }
  70946. this._rightStick = newValues;
  70947. },
  70948. enumerable: true,
  70949. configurable: true
  70950. });
  70951. Gamepad.prototype.update = function () {
  70952. if (this._leftStick) {
  70953. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70954. if (this._invertLeftStickY) {
  70955. this.leftStick.y *= -1;
  70956. }
  70957. }
  70958. if (this._rightStick) {
  70959. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70960. }
  70961. };
  70962. Gamepad.prototype.dispose = function () {
  70963. };
  70964. Gamepad.GAMEPAD = 0;
  70965. Gamepad.GENERIC = 1;
  70966. Gamepad.XBOX = 2;
  70967. Gamepad.POSE_ENABLED = 3;
  70968. return Gamepad;
  70969. }());
  70970. BABYLON.Gamepad = Gamepad;
  70971. var GenericPad = /** @class */ (function (_super) {
  70972. __extends(GenericPad, _super);
  70973. function GenericPad(id, index, browserGamepad) {
  70974. var _this = _super.call(this, id, index, browserGamepad) || this;
  70975. _this.onButtonDownObservable = new BABYLON.Observable();
  70976. _this.onButtonUpObservable = new BABYLON.Observable();
  70977. _this.type = Gamepad.GENERIC;
  70978. _this._buttons = new Array(browserGamepad.buttons.length);
  70979. return _this;
  70980. }
  70981. GenericPad.prototype.onbuttondown = function (callback) {
  70982. this._onbuttondown = callback;
  70983. };
  70984. GenericPad.prototype.onbuttonup = function (callback) {
  70985. this._onbuttonup = callback;
  70986. };
  70987. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70988. if (newValue !== currentValue) {
  70989. if (newValue === 1) {
  70990. if (this._onbuttondown) {
  70991. this._onbuttondown(buttonIndex);
  70992. }
  70993. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70994. }
  70995. if (newValue === 0) {
  70996. if (this._onbuttonup) {
  70997. this._onbuttonup(buttonIndex);
  70998. }
  70999. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71000. }
  71001. }
  71002. return newValue;
  71003. };
  71004. GenericPad.prototype.update = function () {
  71005. _super.prototype.update.call(this);
  71006. for (var index = 0; index < this._buttons.length; index++) {
  71007. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71008. }
  71009. };
  71010. GenericPad.prototype.dispose = function () {
  71011. _super.prototype.dispose.call(this);
  71012. this.onButtonDownObservable.clear();
  71013. this.onButtonUpObservable.clear();
  71014. };
  71015. return GenericPad;
  71016. }(Gamepad));
  71017. BABYLON.GenericPad = GenericPad;
  71018. })(BABYLON || (BABYLON = {}));
  71019. //# sourceMappingURL=babylon.gamepad.js.map
  71020. var BABYLON;
  71021. (function (BABYLON) {
  71022. /**
  71023. * Defines supported buttons for XBox360 compatible gamepads
  71024. */
  71025. var Xbox360Button;
  71026. (function (Xbox360Button) {
  71027. /** A */
  71028. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71029. /** B */
  71030. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71031. /** X */
  71032. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71033. /** Y */
  71034. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71035. /** Start */
  71036. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71037. /** Back */
  71038. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71039. /** Left button */
  71040. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71041. /** Right button */
  71042. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71043. /** Left stick */
  71044. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71045. /** Right stick */
  71046. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71047. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71048. /** Defines values for XBox360 DPad */
  71049. var Xbox360Dpad;
  71050. (function (Xbox360Dpad) {
  71051. /** Up */
  71052. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71053. /** Down */
  71054. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71055. /** Left */
  71056. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71057. /** Right */
  71058. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71059. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71060. /**
  71061. * Defines a XBox360 gamepad
  71062. */
  71063. var Xbox360Pad = /** @class */ (function (_super) {
  71064. __extends(Xbox360Pad, _super);
  71065. /**
  71066. * Creates a new XBox360 gamepad object
  71067. * @param id defines the id of this gamepad
  71068. * @param index defines its index
  71069. * @param gamepad defines the internal HTML gamepad object
  71070. * @param xboxOne defines if it is a XBox One gamepad
  71071. */
  71072. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71073. if (xboxOne === void 0) { xboxOne = false; }
  71074. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71075. _this._leftTrigger = 0;
  71076. _this._rightTrigger = 0;
  71077. /** Observable raised when a button is pressed */
  71078. _this.onButtonDownObservable = new BABYLON.Observable();
  71079. /** Observable raised when a button is released */
  71080. _this.onButtonUpObservable = new BABYLON.Observable();
  71081. /** Observable raised when a pad is pressed */
  71082. _this.onPadDownObservable = new BABYLON.Observable();
  71083. /** Observable raised when a pad is released */
  71084. _this.onPadUpObservable = new BABYLON.Observable();
  71085. _this._buttonA = 0;
  71086. _this._buttonB = 0;
  71087. _this._buttonX = 0;
  71088. _this._buttonY = 0;
  71089. _this._buttonBack = 0;
  71090. _this._buttonStart = 0;
  71091. _this._buttonLB = 0;
  71092. _this._buttonRB = 0;
  71093. _this._buttonLeftStick = 0;
  71094. _this._buttonRightStick = 0;
  71095. _this._dPadUp = 0;
  71096. _this._dPadDown = 0;
  71097. _this._dPadLeft = 0;
  71098. _this._dPadRight = 0;
  71099. _this._isXboxOnePad = false;
  71100. _this.type = BABYLON.Gamepad.XBOX;
  71101. _this._isXboxOnePad = xboxOne;
  71102. return _this;
  71103. }
  71104. /**
  71105. * Defines the callback to call when left trigger is pressed
  71106. * @param callback defines the callback to use
  71107. */
  71108. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71109. this._onlefttriggerchanged = callback;
  71110. };
  71111. /**
  71112. * Defines the callback to call when right trigger is pressed
  71113. * @param callback defines the callback to use
  71114. */
  71115. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71116. this._onrighttriggerchanged = callback;
  71117. };
  71118. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71119. /**
  71120. * Gets or sets left trigger value
  71121. */
  71122. get: function () {
  71123. return this._leftTrigger;
  71124. },
  71125. set: function (newValue) {
  71126. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71127. this._onlefttriggerchanged(newValue);
  71128. }
  71129. this._leftTrigger = newValue;
  71130. },
  71131. enumerable: true,
  71132. configurable: true
  71133. });
  71134. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71135. /**
  71136. * Gets or sets right trigger value
  71137. */
  71138. get: function () {
  71139. return this._rightTrigger;
  71140. },
  71141. set: function (newValue) {
  71142. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71143. this._onrighttriggerchanged(newValue);
  71144. }
  71145. this._rightTrigger = newValue;
  71146. },
  71147. enumerable: true,
  71148. configurable: true
  71149. });
  71150. /**
  71151. * Defines the callback to call when a button is pressed
  71152. * @param callback defines the callback to use
  71153. */
  71154. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71155. this._onbuttondown = callback;
  71156. };
  71157. /**
  71158. * Defines the callback to call when a button is released
  71159. * @param callback defines the callback to use
  71160. */
  71161. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71162. this._onbuttonup = callback;
  71163. };
  71164. /**
  71165. * Defines the callback to call when a pad is pressed
  71166. * @param callback defines the callback to use
  71167. */
  71168. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71169. this._ondpaddown = callback;
  71170. };
  71171. /**
  71172. * Defines the callback to call when a pad is released
  71173. * @param callback defines the callback to use
  71174. */
  71175. Xbox360Pad.prototype.ondpadup = function (callback) {
  71176. this._ondpadup = callback;
  71177. };
  71178. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71179. if (newValue !== currentValue) {
  71180. if (newValue === 1) {
  71181. if (this._onbuttondown) {
  71182. this._onbuttondown(buttonType);
  71183. }
  71184. this.onButtonDownObservable.notifyObservers(buttonType);
  71185. }
  71186. if (newValue === 0) {
  71187. if (this._onbuttonup) {
  71188. this._onbuttonup(buttonType);
  71189. }
  71190. this.onButtonUpObservable.notifyObservers(buttonType);
  71191. }
  71192. }
  71193. return newValue;
  71194. };
  71195. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71196. if (newValue !== currentValue) {
  71197. if (newValue === 1) {
  71198. if (this._ondpaddown) {
  71199. this._ondpaddown(buttonType);
  71200. }
  71201. this.onPadDownObservable.notifyObservers(buttonType);
  71202. }
  71203. if (newValue === 0) {
  71204. if (this._ondpadup) {
  71205. this._ondpadup(buttonType);
  71206. }
  71207. this.onPadUpObservable.notifyObservers(buttonType);
  71208. }
  71209. }
  71210. return newValue;
  71211. };
  71212. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71213. /** Gets or sets value of A button */
  71214. get: function () {
  71215. return this._buttonA;
  71216. },
  71217. set: function (value) {
  71218. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71219. },
  71220. enumerable: true,
  71221. configurable: true
  71222. });
  71223. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71224. /** Gets or sets value of B button */
  71225. get: function () {
  71226. return this._buttonB;
  71227. },
  71228. set: function (value) {
  71229. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71230. },
  71231. enumerable: true,
  71232. configurable: true
  71233. });
  71234. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71235. /** Gets or sets value of X button */
  71236. get: function () {
  71237. return this._buttonX;
  71238. },
  71239. set: function (value) {
  71240. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71241. },
  71242. enumerable: true,
  71243. configurable: true
  71244. });
  71245. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71246. /** Gets or sets value of Y button */
  71247. get: function () {
  71248. return this._buttonY;
  71249. },
  71250. set: function (value) {
  71251. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71252. },
  71253. enumerable: true,
  71254. configurable: true
  71255. });
  71256. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71257. /** Gets or sets value of Start button */
  71258. get: function () {
  71259. return this._buttonStart;
  71260. },
  71261. set: function (value) {
  71262. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71263. },
  71264. enumerable: true,
  71265. configurable: true
  71266. });
  71267. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71268. /** Gets or sets value of Back button */
  71269. get: function () {
  71270. return this._buttonBack;
  71271. },
  71272. set: function (value) {
  71273. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71274. },
  71275. enumerable: true,
  71276. configurable: true
  71277. });
  71278. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71279. /** Gets or sets value of Left button */
  71280. get: function () {
  71281. return this._buttonLB;
  71282. },
  71283. set: function (value) {
  71284. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71285. },
  71286. enumerable: true,
  71287. configurable: true
  71288. });
  71289. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71290. /** Gets or sets value of Right button */
  71291. get: function () {
  71292. return this._buttonRB;
  71293. },
  71294. set: function (value) {
  71295. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71296. },
  71297. enumerable: true,
  71298. configurable: true
  71299. });
  71300. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71301. /** Gets or sets value of left stick */
  71302. get: function () {
  71303. return this._buttonLeftStick;
  71304. },
  71305. set: function (value) {
  71306. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71307. },
  71308. enumerable: true,
  71309. configurable: true
  71310. });
  71311. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71312. /** Gets or sets value of right stick */
  71313. get: function () {
  71314. return this._buttonRightStick;
  71315. },
  71316. set: function (value) {
  71317. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71318. },
  71319. enumerable: true,
  71320. configurable: true
  71321. });
  71322. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71323. /** Gets or sets value of DPad up */
  71324. get: function () {
  71325. return this._dPadUp;
  71326. },
  71327. set: function (value) {
  71328. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71329. },
  71330. enumerable: true,
  71331. configurable: true
  71332. });
  71333. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71334. /** Gets or sets value of DPad down */
  71335. get: function () {
  71336. return this._dPadDown;
  71337. },
  71338. set: function (value) {
  71339. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71340. },
  71341. enumerable: true,
  71342. configurable: true
  71343. });
  71344. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71345. /** Gets or sets value of DPad left */
  71346. get: function () {
  71347. return this._dPadLeft;
  71348. },
  71349. set: function (value) {
  71350. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71351. },
  71352. enumerable: true,
  71353. configurable: true
  71354. });
  71355. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71356. /** Gets or sets value of DPad right */
  71357. get: function () {
  71358. return this._dPadRight;
  71359. },
  71360. set: function (value) {
  71361. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71362. },
  71363. enumerable: true,
  71364. configurable: true
  71365. });
  71366. /**
  71367. * Force the gamepad to synchronize with device values
  71368. */
  71369. Xbox360Pad.prototype.update = function () {
  71370. _super.prototype.update.call(this);
  71371. if (this._isXboxOnePad) {
  71372. this.buttonA = this.browserGamepad.buttons[0].value;
  71373. this.buttonB = this.browserGamepad.buttons[1].value;
  71374. this.buttonX = this.browserGamepad.buttons[2].value;
  71375. this.buttonY = this.browserGamepad.buttons[3].value;
  71376. this.buttonLB = this.browserGamepad.buttons[4].value;
  71377. this.buttonRB = this.browserGamepad.buttons[5].value;
  71378. this.leftTrigger = this.browserGamepad.axes[2];
  71379. this.rightTrigger = this.browserGamepad.axes[5];
  71380. this.buttonBack = this.browserGamepad.buttons[9].value;
  71381. this.buttonStart = this.browserGamepad.buttons[8].value;
  71382. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71383. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71384. this.dPadUp = this.browserGamepad.buttons[11].value;
  71385. this.dPadDown = this.browserGamepad.buttons[12].value;
  71386. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71387. this.dPadRight = this.browserGamepad.buttons[14].value;
  71388. }
  71389. else {
  71390. this.buttonA = this.browserGamepad.buttons[0].value;
  71391. this.buttonB = this.browserGamepad.buttons[1].value;
  71392. this.buttonX = this.browserGamepad.buttons[2].value;
  71393. this.buttonY = this.browserGamepad.buttons[3].value;
  71394. this.buttonLB = this.browserGamepad.buttons[4].value;
  71395. this.buttonRB = this.browserGamepad.buttons[5].value;
  71396. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71397. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71398. this.buttonBack = this.browserGamepad.buttons[8].value;
  71399. this.buttonStart = this.browserGamepad.buttons[9].value;
  71400. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71401. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71402. this.dPadUp = this.browserGamepad.buttons[12].value;
  71403. this.dPadDown = this.browserGamepad.buttons[13].value;
  71404. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71405. this.dPadRight = this.browserGamepad.buttons[15].value;
  71406. }
  71407. };
  71408. Xbox360Pad.prototype.dispose = function () {
  71409. _super.prototype.dispose.call(this);
  71410. this.onButtonDownObservable.clear();
  71411. this.onButtonUpObservable.clear();
  71412. this.onPadDownObservable.clear();
  71413. this.onPadUpObservable.clear();
  71414. };
  71415. return Xbox360Pad;
  71416. }(BABYLON.Gamepad));
  71417. BABYLON.Xbox360Pad = Xbox360Pad;
  71418. })(BABYLON || (BABYLON = {}));
  71419. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71420. var BABYLON;
  71421. (function (BABYLON) {
  71422. /**
  71423. * Defines the types of pose enabled controllers that are supported
  71424. */
  71425. var PoseEnabledControllerType;
  71426. (function (PoseEnabledControllerType) {
  71427. /**
  71428. * HTC Vive
  71429. */
  71430. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71431. /**
  71432. * Oculus Rift
  71433. */
  71434. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71435. /**
  71436. * Windows mixed reality
  71437. */
  71438. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71439. /**
  71440. * Samsung gear VR
  71441. */
  71442. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71443. /**
  71444. * Google Daydream
  71445. */
  71446. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71447. /**
  71448. * Generic
  71449. */
  71450. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71451. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71452. /**
  71453. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71454. */
  71455. var PoseEnabledControllerHelper = /** @class */ (function () {
  71456. function PoseEnabledControllerHelper() {
  71457. }
  71458. /**
  71459. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71460. * @param vrGamepad the gamepad to initialized
  71461. * @returns a vr controller of the type the gamepad identified as
  71462. */
  71463. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71464. // Oculus Touch
  71465. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71466. return new BABYLON.OculusTouchController(vrGamepad);
  71467. }
  71468. // Windows Mixed Reality controllers
  71469. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71470. return new BABYLON.WindowsMotionController(vrGamepad);
  71471. }
  71472. // HTC Vive
  71473. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71474. return new BABYLON.ViveController(vrGamepad);
  71475. }
  71476. // Samsung/Oculus Gear VR or Oculus Go
  71477. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71478. return new BABYLON.GearVRController(vrGamepad);
  71479. }
  71480. // Google Daydream
  71481. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71482. return new BABYLON.DaydreamController(vrGamepad);
  71483. }
  71484. // Generic
  71485. else {
  71486. return new BABYLON.GenericController(vrGamepad);
  71487. }
  71488. };
  71489. return PoseEnabledControllerHelper;
  71490. }());
  71491. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71492. /**
  71493. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71494. */
  71495. var PoseEnabledController = /** @class */ (function (_super) {
  71496. __extends(PoseEnabledController, _super);
  71497. /**
  71498. * Creates a new PoseEnabledController from a gamepad
  71499. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71500. */
  71501. function PoseEnabledController(browserGamepad) {
  71502. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71503. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71504. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71505. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71506. /**
  71507. * The device position in babylon space
  71508. */
  71509. _this.devicePosition = BABYLON.Vector3.Zero();
  71510. /**
  71511. * The device rotation in babylon space
  71512. */
  71513. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71514. /**
  71515. * The scale factor of the device in babylon space
  71516. */
  71517. _this.deviceScaleFactor = 1;
  71518. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71519. /**
  71520. * Internal, matrix used to convert room space to babylon space
  71521. */
  71522. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71523. /**
  71524. * Node to be used when casting a ray from the controller
  71525. */
  71526. _this._pointingPoseNode = null;
  71527. _this._workingMatrix = BABYLON.Matrix.Identity();
  71528. /**
  71529. * @hidden
  71530. */
  71531. _this._meshAttachedObservable = new BABYLON.Observable();
  71532. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71533. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71534. _this.position = BABYLON.Vector3.Zero();
  71535. _this.rotationQuaternion = new BABYLON.Quaternion();
  71536. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71537. _this._calculatedRotation = new BABYLON.Quaternion();
  71538. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71539. return _this;
  71540. }
  71541. /**
  71542. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71543. */
  71544. PoseEnabledController.prototype.update = function () {
  71545. _super.prototype.update.call(this);
  71546. var pose = this.browserGamepad.pose;
  71547. this.updateFromDevice(pose);
  71548. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71549. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71550. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71551. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71552. if (this._mesh) {
  71553. this._mesh.position.copyFrom(this.devicePosition);
  71554. if (this._mesh.rotationQuaternion) {
  71555. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71556. }
  71557. }
  71558. };
  71559. /**
  71560. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71561. * @param poseData raw pose fromthe device
  71562. */
  71563. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71564. if (poseData) {
  71565. this.rawPose = poseData;
  71566. if (poseData.position) {
  71567. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71568. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71569. this._deviceRoomPosition.z *= -1;
  71570. }
  71571. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71572. this._calculatedPosition.addInPlace(this.position);
  71573. }
  71574. var pose = this.rawPose;
  71575. if (poseData.orientation && pose.orientation) {
  71576. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71577. if (this._mesh) {
  71578. if (this._mesh.getScene().useRightHandedSystem) {
  71579. this._deviceRoomRotationQuaternion.z *= -1;
  71580. this._deviceRoomRotationQuaternion.w *= -1;
  71581. }
  71582. else {
  71583. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71584. }
  71585. }
  71586. // if the camera is set, rotate to the camera's rotation
  71587. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71588. }
  71589. }
  71590. };
  71591. /**
  71592. * Attaches a mesh to the controller
  71593. * @param mesh the mesh to be attached
  71594. */
  71595. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71596. if (this._mesh) {
  71597. this._mesh.parent = null;
  71598. }
  71599. this._mesh = mesh;
  71600. if (this._poseControlledCamera) {
  71601. this._mesh.parent = this._poseControlledCamera;
  71602. }
  71603. if (!this._mesh.rotationQuaternion) {
  71604. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71605. }
  71606. this._meshAttachedObservable.notifyObservers(mesh);
  71607. };
  71608. /**
  71609. * Attaches the controllers mesh to a camera
  71610. * @param camera the camera the mesh should be attached to
  71611. */
  71612. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71613. this._poseControlledCamera = camera;
  71614. if (this._mesh) {
  71615. this._mesh.parent = this._poseControlledCamera;
  71616. }
  71617. };
  71618. /**
  71619. * Disposes of the controller
  71620. */
  71621. PoseEnabledController.prototype.dispose = function () {
  71622. if (this._mesh) {
  71623. this._mesh.dispose();
  71624. }
  71625. this._mesh = null;
  71626. _super.prototype.dispose.call(this);
  71627. };
  71628. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71629. /**
  71630. * The mesh that is attached to the controller
  71631. */
  71632. get: function () {
  71633. return this._mesh;
  71634. },
  71635. enumerable: true,
  71636. configurable: true
  71637. });
  71638. /**
  71639. * Gets the ray of the controller in the direction the controller is pointing
  71640. * @param length the length the resulting ray should be
  71641. * @returns a ray in the direction the controller is pointing
  71642. */
  71643. PoseEnabledController.prototype.getForwardRay = function (length) {
  71644. if (length === void 0) { length = 100; }
  71645. if (!this.mesh) {
  71646. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71647. }
  71648. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71649. var origin = m.getTranslation();
  71650. var forward = new BABYLON.Vector3(0, 0, -1);
  71651. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71652. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71653. return new BABYLON.Ray(origin, direction, length);
  71654. };
  71655. /**
  71656. * Name of the child mesh that can be used to cast a ray from the controller
  71657. */
  71658. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71659. return PoseEnabledController;
  71660. }(BABYLON.Gamepad));
  71661. BABYLON.PoseEnabledController = PoseEnabledController;
  71662. })(BABYLON || (BABYLON = {}));
  71663. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71664. var BABYLON;
  71665. (function (BABYLON) {
  71666. /**
  71667. * Defines the WebVRController object that represents controllers tracked in 3D space
  71668. */
  71669. var WebVRController = /** @class */ (function (_super) {
  71670. __extends(WebVRController, _super);
  71671. /**
  71672. * Creates a new WebVRController from a gamepad
  71673. * @param vrGamepad the gamepad that the WebVRController should be created from
  71674. */
  71675. function WebVRController(vrGamepad) {
  71676. var _this = _super.call(this, vrGamepad) || this;
  71677. // Observables
  71678. /**
  71679. * Fired when the trigger state has changed
  71680. */
  71681. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71682. /**
  71683. * Fired when the main button state has changed
  71684. */
  71685. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71686. /**
  71687. * Fired when the secondary button state has changed
  71688. */
  71689. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71690. /**
  71691. * Fired when the pad state has changed
  71692. */
  71693. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71694. /**
  71695. * Fired when controllers stick values have changed
  71696. */
  71697. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71698. /**
  71699. * X and Y axis corrisponding to the controllers joystick
  71700. */
  71701. _this.pad = { x: 0, y: 0 };
  71702. // avoid GC, store state in a tmp object
  71703. _this._changes = {
  71704. pressChanged: false,
  71705. touchChanged: false,
  71706. valueChanged: false,
  71707. changed: false
  71708. };
  71709. _this._buttons = new Array(vrGamepad.buttons.length);
  71710. _this.hand = vrGamepad.hand;
  71711. return _this;
  71712. }
  71713. /**
  71714. * Fired when a controller button's state has changed
  71715. * @param callback the callback containing the button that was modified
  71716. */
  71717. WebVRController.prototype.onButtonStateChange = function (callback) {
  71718. this._onButtonStateChange = callback;
  71719. };
  71720. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71721. /**
  71722. * The default controller model for the controller
  71723. */
  71724. get: function () {
  71725. return this._defaultModel;
  71726. },
  71727. enumerable: true,
  71728. configurable: true
  71729. });
  71730. /**
  71731. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71732. */
  71733. WebVRController.prototype.update = function () {
  71734. _super.prototype.update.call(this);
  71735. for (var index = 0; index < this._buttons.length; index++) {
  71736. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71737. }
  71738. ;
  71739. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71740. this.pad.x = this.leftStick.x;
  71741. this.pad.y = this.leftStick.y;
  71742. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71743. }
  71744. };
  71745. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71746. if (!newState) {
  71747. newState = {
  71748. pressed: false,
  71749. touched: false,
  71750. value: 0
  71751. };
  71752. }
  71753. if (!currentState) {
  71754. this._buttons[buttonIndex] = {
  71755. pressed: newState.pressed,
  71756. touched: newState.touched,
  71757. value: newState.value
  71758. };
  71759. return;
  71760. }
  71761. this._checkChanges(newState, currentState);
  71762. if (this._changes.changed) {
  71763. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71764. this._handleButtonChange(buttonIndex, newState, this._changes);
  71765. }
  71766. this._buttons[buttonIndex].pressed = newState.pressed;
  71767. this._buttons[buttonIndex].touched = newState.touched;
  71768. // oculus triggers are never 0, thou not touched.
  71769. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71770. };
  71771. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71772. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71773. this._changes.touchChanged = newState.touched !== currentState.touched;
  71774. this._changes.valueChanged = newState.value !== currentState.value;
  71775. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71776. return this._changes;
  71777. };
  71778. /**
  71779. * Disposes of th webVRCOntroller
  71780. */
  71781. WebVRController.prototype.dispose = function () {
  71782. _super.prototype.dispose.call(this);
  71783. this.onTriggerStateChangedObservable.clear();
  71784. this.onMainButtonStateChangedObservable.clear();
  71785. this.onSecondaryButtonStateChangedObservable.clear();
  71786. this.onPadStateChangedObservable.clear();
  71787. this.onPadValuesChangedObservable.clear();
  71788. };
  71789. return WebVRController;
  71790. }(BABYLON.PoseEnabledController));
  71791. BABYLON.WebVRController = WebVRController;
  71792. })(BABYLON || (BABYLON = {}));
  71793. //# sourceMappingURL=babylon.webVRController.js.map
  71794. var BABYLON;
  71795. (function (BABYLON) {
  71796. /**
  71797. * Oculus Touch Controller
  71798. */
  71799. var OculusTouchController = /** @class */ (function (_super) {
  71800. __extends(OculusTouchController, _super);
  71801. /**
  71802. * Creates a new OculusTouchController from a gamepad
  71803. * @param vrGamepad the gamepad that the controller should be created from
  71804. */
  71805. function OculusTouchController(vrGamepad) {
  71806. var _this = _super.call(this, vrGamepad) || this;
  71807. /**
  71808. * Fired when the secondary trigger on this controller is modified
  71809. */
  71810. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71811. /**
  71812. * Fired when the thumb rest on this controller is modified
  71813. */
  71814. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71815. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71816. return _this;
  71817. }
  71818. /**
  71819. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71820. * @param scene scene in which to add meshes
  71821. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71822. */
  71823. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71824. var _this = this;
  71825. var meshName;
  71826. // Hand
  71827. if (this.hand === 'left') {
  71828. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71829. }
  71830. else { // Right is the default if no hand is specified
  71831. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71832. }
  71833. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71834. /*
  71835. Parent Mesh name: oculus_touch_left
  71836. - body
  71837. - trigger
  71838. - thumbstick
  71839. - grip
  71840. - button_y
  71841. - button_x
  71842. - button_enter
  71843. */
  71844. _this._defaultModel = newMeshes[1];
  71845. _this.attachToMesh(_this._defaultModel);
  71846. if (meshLoaded) {
  71847. meshLoaded(_this._defaultModel);
  71848. }
  71849. });
  71850. };
  71851. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71852. /**
  71853. * Fired when the A button on this controller is modified
  71854. */
  71855. get: function () {
  71856. if (this.hand === 'right') {
  71857. return this.onMainButtonStateChangedObservable;
  71858. }
  71859. else {
  71860. throw new Error('No A button on left hand');
  71861. }
  71862. },
  71863. enumerable: true,
  71864. configurable: true
  71865. });
  71866. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71867. /**
  71868. * Fired when the B button on this controller is modified
  71869. */
  71870. get: function () {
  71871. if (this.hand === 'right') {
  71872. return this.onSecondaryButtonStateChangedObservable;
  71873. }
  71874. else {
  71875. throw new Error('No B button on left hand');
  71876. }
  71877. },
  71878. enumerable: true,
  71879. configurable: true
  71880. });
  71881. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71882. /**
  71883. * Fired when the X button on this controller is modified
  71884. */
  71885. get: function () {
  71886. if (this.hand === 'left') {
  71887. return this.onMainButtonStateChangedObservable;
  71888. }
  71889. else {
  71890. throw new Error('No X button on right hand');
  71891. }
  71892. },
  71893. enumerable: true,
  71894. configurable: true
  71895. });
  71896. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71897. /**
  71898. * Fired when the Y button on this controller is modified
  71899. */
  71900. get: function () {
  71901. if (this.hand === 'left') {
  71902. return this.onSecondaryButtonStateChangedObservable;
  71903. }
  71904. else {
  71905. throw new Error('No Y button on right hand');
  71906. }
  71907. },
  71908. enumerable: true,
  71909. configurable: true
  71910. });
  71911. /**
  71912. * Called once for each button that changed state since the last frame
  71913. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71914. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71915. * 2) secondary trigger (same)
  71916. * 3) A (right) X (left), touch, pressed = value
  71917. * 4) B / Y
  71918. * 5) thumb rest
  71919. * @param buttonIdx Which button index changed
  71920. * @param state New state of the button
  71921. * @param changes Which properties on the state changed since last frame
  71922. */
  71923. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71924. var notifyObject = state; //{ state: state, changes: changes };
  71925. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71926. switch (buttonIdx) {
  71927. case 0:
  71928. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71929. return;
  71930. case 1: // index trigger
  71931. if (this._defaultModel) {
  71932. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71933. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71934. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71935. }
  71936. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71937. return;
  71938. case 2: // secondary trigger
  71939. if (this._defaultModel) {
  71940. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71941. }
  71942. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71943. return;
  71944. case 3:
  71945. if (this._defaultModel) {
  71946. if (notifyObject.pressed) {
  71947. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71948. }
  71949. else {
  71950. (this._defaultModel.getChildren()[1]).position.y = 0;
  71951. }
  71952. }
  71953. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71954. return;
  71955. case 4:
  71956. if (this._defaultModel) {
  71957. if (notifyObject.pressed) {
  71958. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71959. }
  71960. else {
  71961. (this._defaultModel.getChildren()[2]).position.y = 0;
  71962. }
  71963. }
  71964. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71965. return;
  71966. case 5:
  71967. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71968. return;
  71969. }
  71970. };
  71971. /**
  71972. * Base Url for the controller model.
  71973. */
  71974. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71975. /**
  71976. * File name for the left controller model.
  71977. */
  71978. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71979. /**
  71980. * File name for the right controller model.
  71981. */
  71982. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71983. return OculusTouchController;
  71984. }(BABYLON.WebVRController));
  71985. BABYLON.OculusTouchController = OculusTouchController;
  71986. })(BABYLON || (BABYLON = {}));
  71987. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71988. var BABYLON;
  71989. (function (BABYLON) {
  71990. /**
  71991. * Vive Controller
  71992. */
  71993. var ViveController = /** @class */ (function (_super) {
  71994. __extends(ViveController, _super);
  71995. /**
  71996. * Creates a new ViveController from a gamepad
  71997. * @param vrGamepad the gamepad that the controller should be created from
  71998. */
  71999. function ViveController(vrGamepad) {
  72000. var _this = _super.call(this, vrGamepad) || this;
  72001. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72002. _this._invertLeftStickY = true;
  72003. return _this;
  72004. }
  72005. /**
  72006. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72007. * @param scene scene in which to add meshes
  72008. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72009. */
  72010. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72011. var _this = this;
  72012. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72013. /*
  72014. Parent Mesh name: ViveWand
  72015. - body
  72016. - r_gripper
  72017. - l_gripper
  72018. - menu_button
  72019. - system_button
  72020. - trackpad
  72021. - trigger
  72022. - LED
  72023. */
  72024. _this._defaultModel = newMeshes[1];
  72025. _this.attachToMesh(_this._defaultModel);
  72026. if (meshLoaded) {
  72027. meshLoaded(_this._defaultModel);
  72028. }
  72029. });
  72030. };
  72031. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72032. /**
  72033. * Fired when the left button on this controller is modified
  72034. */
  72035. get: function () {
  72036. return this.onMainButtonStateChangedObservable;
  72037. },
  72038. enumerable: true,
  72039. configurable: true
  72040. });
  72041. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72042. /**
  72043. * Fired when the right button on this controller is modified
  72044. */
  72045. get: function () {
  72046. return this.onMainButtonStateChangedObservable;
  72047. },
  72048. enumerable: true,
  72049. configurable: true
  72050. });
  72051. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72052. /**
  72053. * Fired when the menu button on this controller is modified
  72054. */
  72055. get: function () {
  72056. return this.onSecondaryButtonStateChangedObservable;
  72057. },
  72058. enumerable: true,
  72059. configurable: true
  72060. });
  72061. /**
  72062. * Called once for each button that changed state since the last frame
  72063. * Vive mapping:
  72064. * 0: touchpad
  72065. * 1: trigger
  72066. * 2: left AND right buttons
  72067. * 3: menu button
  72068. * @param buttonIdx Which button index changed
  72069. * @param state New state of the button
  72070. * @param changes Which properties on the state changed since last frame
  72071. */
  72072. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72073. var notifyObject = state; //{ state: state, changes: changes };
  72074. switch (buttonIdx) {
  72075. case 0:
  72076. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72077. return;
  72078. case 1: // index trigger
  72079. if (this._defaultModel) {
  72080. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72081. }
  72082. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72083. return;
  72084. case 2: // left AND right button
  72085. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72086. return;
  72087. case 3:
  72088. if (this._defaultModel) {
  72089. if (notifyObject.pressed) {
  72090. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72091. }
  72092. else {
  72093. (this._defaultModel.getChildren()[2]).position.y = 0;
  72094. }
  72095. }
  72096. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72097. return;
  72098. }
  72099. };
  72100. /**
  72101. * Base Url for the controller model.
  72102. */
  72103. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72104. /**
  72105. * File name for the controller model.
  72106. */
  72107. ViveController.MODEL_FILENAME = 'wand.babylon';
  72108. return ViveController;
  72109. }(BABYLON.WebVRController));
  72110. BABYLON.ViveController = ViveController;
  72111. })(BABYLON || (BABYLON = {}));
  72112. //# sourceMappingURL=babylon.viveController.js.map
  72113. var BABYLON;
  72114. (function (BABYLON) {
  72115. /**
  72116. * Generic Controller
  72117. */
  72118. var GenericController = /** @class */ (function (_super) {
  72119. __extends(GenericController, _super);
  72120. /**
  72121. * Creates a new GenericController from a gamepad
  72122. * @param vrGamepad the gamepad that the controller should be created from
  72123. */
  72124. function GenericController(vrGamepad) {
  72125. return _super.call(this, vrGamepad) || this;
  72126. }
  72127. /**
  72128. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72129. * @param scene scene in which to add meshes
  72130. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72131. */
  72132. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72133. var _this = this;
  72134. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72135. _this._defaultModel = newMeshes[1];
  72136. _this.attachToMesh(_this._defaultModel);
  72137. if (meshLoaded) {
  72138. meshLoaded(_this._defaultModel);
  72139. }
  72140. });
  72141. };
  72142. /**
  72143. * Called once for each button that changed state since the last frame
  72144. * @param buttonIdx Which button index changed
  72145. * @param state New state of the button
  72146. * @param changes Which properties on the state changed since last frame
  72147. */
  72148. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72149. console.log("Button id: " + buttonIdx + "state: ");
  72150. console.dir(state);
  72151. };
  72152. /**
  72153. * Base Url for the controller model.
  72154. */
  72155. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72156. /**
  72157. * File name for the controller model.
  72158. */
  72159. GenericController.MODEL_FILENAME = 'generic.babylon';
  72160. return GenericController;
  72161. }(BABYLON.WebVRController));
  72162. BABYLON.GenericController = GenericController;
  72163. })(BABYLON || (BABYLON = {}));
  72164. //# sourceMappingURL=babylon.genericController.js.map
  72165. var BABYLON;
  72166. (function (BABYLON) {
  72167. /**
  72168. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72169. */
  72170. var LoadedMeshInfo = /** @class */ (function () {
  72171. function LoadedMeshInfo() {
  72172. /**
  72173. * Map of the button meshes contained in the controller
  72174. */
  72175. this.buttonMeshes = {};
  72176. /**
  72177. * Map of the axis meshes contained in the controller
  72178. */
  72179. this.axisMeshes = {};
  72180. }
  72181. return LoadedMeshInfo;
  72182. }());
  72183. /**
  72184. * Defines the WindowsMotionController object that the state of the windows motion controller
  72185. */
  72186. var WindowsMotionController = /** @class */ (function (_super) {
  72187. __extends(WindowsMotionController, _super);
  72188. /**
  72189. * Creates a new WindowsMotionController from a gamepad
  72190. * @param vrGamepad the gamepad that the controller should be created from
  72191. */
  72192. function WindowsMotionController(vrGamepad) {
  72193. var _this = _super.call(this, vrGamepad) || this;
  72194. _this._mapping = {
  72195. // Semantic button names
  72196. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72197. // A mapping of the button name to glTF model node name
  72198. // that should be transformed by button value.
  72199. buttonMeshNames: {
  72200. 'trigger': 'SELECT',
  72201. 'menu': 'MENU',
  72202. 'grip': 'GRASP',
  72203. 'thumbstick': 'THUMBSTICK_PRESS',
  72204. 'trackpad': 'TOUCHPAD_PRESS'
  72205. },
  72206. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72207. buttonObservableNames: {
  72208. 'trigger': 'onTriggerStateChangedObservable',
  72209. 'menu': 'onSecondaryButtonStateChangedObservable',
  72210. 'grip': 'onMainButtonStateChangedObservable',
  72211. 'thumbstick': 'onPadStateChangedObservable',
  72212. 'trackpad': 'onTrackpadChangedObservable'
  72213. },
  72214. // A mapping of the axis name to glTF model node name
  72215. // that should be transformed by axis value.
  72216. // This array mirrors the browserGamepad.axes array, such that
  72217. // the mesh corresponding to axis 0 is in this array index 0.
  72218. axisMeshNames: [
  72219. 'THUMBSTICK_X',
  72220. 'THUMBSTICK_Y',
  72221. 'TOUCHPAD_TOUCH_X',
  72222. 'TOUCHPAD_TOUCH_Y'
  72223. ],
  72224. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72225. };
  72226. /**
  72227. * Fired when the trackpad on this controller is clicked
  72228. */
  72229. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72230. /**
  72231. * Fired when the trackpad on this controller is modified
  72232. */
  72233. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72234. /**
  72235. * The current x and y values of this controller's trackpad
  72236. */
  72237. _this.trackpad = { x: 0, y: 0 };
  72238. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72239. _this._loadedMeshInfo = null;
  72240. return _this;
  72241. }
  72242. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72243. /**
  72244. * Fired when the trigger on this controller is modified
  72245. */
  72246. get: function () {
  72247. return this.onTriggerStateChangedObservable;
  72248. },
  72249. enumerable: true,
  72250. configurable: true
  72251. });
  72252. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72253. /**
  72254. * Fired when the menu button on this controller is modified
  72255. */
  72256. get: function () {
  72257. return this.onSecondaryButtonStateChangedObservable;
  72258. },
  72259. enumerable: true,
  72260. configurable: true
  72261. });
  72262. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72263. /**
  72264. * Fired when the grip button on this controller is modified
  72265. */
  72266. get: function () {
  72267. return this.onMainButtonStateChangedObservable;
  72268. },
  72269. enumerable: true,
  72270. configurable: true
  72271. });
  72272. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72273. /**
  72274. * Fired when the thumbstick button on this controller is modified
  72275. */
  72276. get: function () {
  72277. return this.onPadStateChangedObservable;
  72278. },
  72279. enumerable: true,
  72280. configurable: true
  72281. });
  72282. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72283. /**
  72284. * Fired when the touchpad button on this controller is modified
  72285. */
  72286. get: function () {
  72287. return this.onTrackpadChangedObservable;
  72288. },
  72289. enumerable: true,
  72290. configurable: true
  72291. });
  72292. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72293. /**
  72294. * Fired when the touchpad values on this controller are modified
  72295. */
  72296. get: function () {
  72297. return this.onTrackpadValuesChangedObservable;
  72298. },
  72299. enumerable: true,
  72300. configurable: true
  72301. });
  72302. /**
  72303. * Called once per frame by the engine.
  72304. */
  72305. WindowsMotionController.prototype.update = function () {
  72306. _super.prototype.update.call(this);
  72307. if (this.browserGamepad.axes) {
  72308. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72309. this.trackpad.x = this.browserGamepad["axes"][2];
  72310. this.trackpad.y = this.browserGamepad["axes"][3];
  72311. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72312. }
  72313. // Only need to animate axes if there is a loaded mesh
  72314. if (this._loadedMeshInfo) {
  72315. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72316. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72317. }
  72318. }
  72319. }
  72320. };
  72321. /**
  72322. * Called once for each button that changed state since the last frame
  72323. * @param buttonIdx Which button index changed
  72324. * @param state New state of the button
  72325. * @param changes Which properties on the state changed since last frame
  72326. */
  72327. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72328. var buttonName = this._mapping.buttons[buttonIdx];
  72329. if (!buttonName) {
  72330. return;
  72331. }
  72332. // Only emit events for buttons that we know how to map from index to name
  72333. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72334. if (observable) {
  72335. observable.notifyObservers(state);
  72336. }
  72337. this._lerpButtonTransform(buttonName, state.value);
  72338. };
  72339. /**
  72340. * Moves the buttons on the controller mesh based on their current state
  72341. * @param buttonName the name of the button to move
  72342. * @param buttonValue the value of the button which determines the buttons new position
  72343. */
  72344. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72345. // If there is no loaded mesh, there is nothing to transform.
  72346. if (!this._loadedMeshInfo) {
  72347. return;
  72348. }
  72349. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72350. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72351. return;
  72352. }
  72353. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72354. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72355. };
  72356. /**
  72357. * Moves the axis on the controller mesh based on its current state
  72358. * @param axis the index of the axis
  72359. * @param axisValue the value of the axis which determines the meshes new position
  72360. * @hidden
  72361. */
  72362. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72363. if (!this._loadedMeshInfo) {
  72364. return;
  72365. }
  72366. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72367. if (!meshInfo) {
  72368. return;
  72369. }
  72370. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72371. return;
  72372. }
  72373. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72374. var lerpValue = axisValue * 0.5 + 0.5;
  72375. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72376. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72377. };
  72378. /**
  72379. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72380. * @param scene scene in which to add meshes
  72381. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72382. */
  72383. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72384. var _this = this;
  72385. if (forceDefault === void 0) { forceDefault = false; }
  72386. var path;
  72387. var filename;
  72388. // Checking if GLB loader is present
  72389. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72390. // Determine the device specific folder based on the ID suffix
  72391. var device = 'default';
  72392. if (this.id && !forceDefault) {
  72393. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72394. device = ((match && match[0]) || device);
  72395. }
  72396. // Hand
  72397. if (this.hand === 'left') {
  72398. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72399. }
  72400. else { // Right is the default if no hand is specified
  72401. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72402. }
  72403. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72404. }
  72405. else {
  72406. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72407. path = BABYLON.GenericController.MODEL_BASE_URL;
  72408. filename = BABYLON.GenericController.MODEL_FILENAME;
  72409. }
  72410. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72411. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72412. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72413. if (!_this._loadedMeshInfo) {
  72414. return;
  72415. }
  72416. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72417. _this.attachToMesh(_this._defaultModel);
  72418. if (meshLoaded) {
  72419. meshLoaded(_this._defaultModel);
  72420. }
  72421. }, null, function (scene, message) {
  72422. BABYLON.Tools.Log(message);
  72423. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72424. if (!forceDefault) {
  72425. _this.initControllerMesh(scene, meshLoaded, true);
  72426. }
  72427. });
  72428. };
  72429. /**
  72430. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72431. * can be transformed by button presses and axes values, based on this._mapping.
  72432. *
  72433. * @param scene scene in which the meshes exist
  72434. * @param meshes list of meshes that make up the controller model to process
  72435. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72436. */
  72437. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72438. var loadedMeshInfo = null;
  72439. // Create a new mesh to contain the glTF hierarchy
  72440. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72441. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72442. var childMesh = null;
  72443. for (var i = 0; i < meshes.length; i++) {
  72444. var mesh = meshes[i];
  72445. if (!mesh.parent) {
  72446. // Exclude controller meshes from picking results
  72447. mesh.isPickable = false;
  72448. // Handle root node, attach to the new parentMesh
  72449. childMesh = mesh;
  72450. break;
  72451. }
  72452. }
  72453. if (childMesh) {
  72454. childMesh.setParent(parentMesh);
  72455. // Create our mesh info. Note that this method will always return non-null.
  72456. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72457. }
  72458. else {
  72459. BABYLON.Tools.Warn('Could not find root node in model file.');
  72460. }
  72461. return loadedMeshInfo;
  72462. };
  72463. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72464. var loadedMeshInfo = new LoadedMeshInfo();
  72465. var i;
  72466. loadedMeshInfo.rootNode = rootNode;
  72467. // Reset the caches
  72468. loadedMeshInfo.buttonMeshes = {};
  72469. loadedMeshInfo.axisMeshes = {};
  72470. // Button Meshes
  72471. for (i = 0; i < this._mapping.buttons.length; i++) {
  72472. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72473. if (!buttonMeshName) {
  72474. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72475. continue;
  72476. }
  72477. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72478. if (!buttonMesh) {
  72479. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72480. continue;
  72481. }
  72482. var buttonMeshInfo = {
  72483. index: i,
  72484. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72485. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72486. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72487. };
  72488. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72489. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72490. }
  72491. else {
  72492. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72493. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72494. '(VALUE: ' + !!buttonMeshInfo.value +
  72495. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72496. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72497. ')');
  72498. }
  72499. }
  72500. // Axis Meshes
  72501. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72502. var axisMeshName = this._mapping.axisMeshNames[i];
  72503. if (!axisMeshName) {
  72504. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72505. continue;
  72506. }
  72507. var axisMesh = getChildByName(rootNode, axisMeshName);
  72508. if (!axisMesh) {
  72509. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72510. continue;
  72511. }
  72512. var axisMeshInfo = {
  72513. index: i,
  72514. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72515. min: getImmediateChildByName(axisMesh, 'MIN'),
  72516. max: getImmediateChildByName(axisMesh, 'MAX')
  72517. };
  72518. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72519. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72520. }
  72521. else {
  72522. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72523. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72524. '(VALUE: ' + !!axisMeshInfo.value +
  72525. ', MIN: ' + !!axisMeshInfo.min +
  72526. ', MAX:' + !!axisMeshInfo.max +
  72527. ')');
  72528. }
  72529. }
  72530. // Pointing Ray
  72531. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72532. if (!loadedMeshInfo.pointingPoseNode) {
  72533. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72534. }
  72535. return loadedMeshInfo;
  72536. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72537. function getChildByName(node, name) {
  72538. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72539. }
  72540. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72541. function getImmediateChildByName(node, name) {
  72542. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72543. }
  72544. };
  72545. /**
  72546. * Gets the ray of the controller in the direction the controller is pointing
  72547. * @param length the length the resulting ray should be
  72548. * @returns a ray in the direction the controller is pointing
  72549. */
  72550. WindowsMotionController.prototype.getForwardRay = function (length) {
  72551. if (length === void 0) { length = 100; }
  72552. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72553. return _super.prototype.getForwardRay.call(this, length);
  72554. }
  72555. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72556. var origin = m.getTranslation();
  72557. var forward = new BABYLON.Vector3(0, 0, -1);
  72558. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72559. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72560. return new BABYLON.Ray(origin, direction, length);
  72561. };
  72562. /**
  72563. * Disposes of the controller
  72564. */
  72565. WindowsMotionController.prototype.dispose = function () {
  72566. _super.prototype.dispose.call(this);
  72567. this.onTrackpadChangedObservable.clear();
  72568. };
  72569. /**
  72570. * The base url used to load the left and right controller models
  72571. */
  72572. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72573. /**
  72574. * The name of the left controller model file
  72575. */
  72576. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72577. /**
  72578. * The name of the right controller model file
  72579. */
  72580. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72581. /**
  72582. * The controller name prefix for this controller type
  72583. */
  72584. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72585. /**
  72586. * The controller id pattern for this controller type
  72587. */
  72588. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72589. return WindowsMotionController;
  72590. }(BABYLON.WebVRController));
  72591. BABYLON.WindowsMotionController = WindowsMotionController;
  72592. })(BABYLON || (BABYLON = {}));
  72593. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72594. var BABYLON;
  72595. (function (BABYLON) {
  72596. /**
  72597. * Gear VR Controller
  72598. */
  72599. var GearVRController = /** @class */ (function (_super) {
  72600. __extends(GearVRController, _super);
  72601. /**
  72602. * Creates a new GearVRController from a gamepad
  72603. * @param vrGamepad the gamepad that the controller should be created from
  72604. */
  72605. function GearVRController(vrGamepad) {
  72606. var _this = _super.call(this, vrGamepad) || this;
  72607. _this._buttonIndexToObservableNameMap = [
  72608. 'onTrackpadChangedObservable',
  72609. 'onTriggerStateChangedObservable' // Trigger
  72610. ];
  72611. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72612. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72613. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72614. return _this;
  72615. }
  72616. /**
  72617. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72618. * @param scene scene in which to add meshes
  72619. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72620. */
  72621. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72622. var _this = this;
  72623. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72624. _this._defaultModel = newMeshes[1];
  72625. _this.attachToMesh(_this._defaultModel);
  72626. if (meshLoaded) {
  72627. meshLoaded(_this._defaultModel);
  72628. }
  72629. });
  72630. };
  72631. /**
  72632. * Called once for each button that changed state since the last frame
  72633. * @param buttonIdx Which button index changed
  72634. * @param state New state of the button
  72635. * @param changes Which properties on the state changed since last frame
  72636. */
  72637. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72638. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72639. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72640. // Only emit events for buttons that we know how to map from index to observable
  72641. var observable = this[observableName];
  72642. if (observable) {
  72643. observable.notifyObservers(state);
  72644. }
  72645. }
  72646. };
  72647. /**
  72648. * Base Url for the controller model.
  72649. */
  72650. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72651. /**
  72652. * File name for the controller model.
  72653. */
  72654. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72655. /**
  72656. * Gamepad Id prefix used to identify this controller.
  72657. */
  72658. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72659. return GearVRController;
  72660. }(BABYLON.WebVRController));
  72661. BABYLON.GearVRController = GearVRController;
  72662. })(BABYLON || (BABYLON = {}));
  72663. //# sourceMappingURL=babylon.gearVRController.js.map
  72664. var BABYLON;
  72665. (function (BABYLON) {
  72666. /**
  72667. * Google Daydream controller
  72668. */
  72669. var DaydreamController = /** @class */ (function (_super) {
  72670. __extends(DaydreamController, _super);
  72671. /**
  72672. * Creates a new DaydreamController from a gamepad
  72673. * @param vrGamepad the gamepad that the controller should be created from
  72674. */
  72675. function DaydreamController(vrGamepad) {
  72676. var _this = _super.call(this, vrGamepad) || this;
  72677. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72678. return _this;
  72679. }
  72680. /**
  72681. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72682. * @param scene scene in which to add meshes
  72683. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72684. */
  72685. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72686. var _this = this;
  72687. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72688. _this._defaultModel = newMeshes[1];
  72689. _this.attachToMesh(_this._defaultModel);
  72690. if (meshLoaded) {
  72691. meshLoaded(_this._defaultModel);
  72692. }
  72693. });
  72694. };
  72695. /**
  72696. * Called once for each button that changed state since the last frame
  72697. * @param buttonIdx Which button index changed
  72698. * @param state New state of the button
  72699. * @param changes Which properties on the state changed since last frame
  72700. */
  72701. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72702. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72703. if (buttonIdx === 0) {
  72704. var observable = this.onTriggerStateChangedObservable;
  72705. if (observable) {
  72706. observable.notifyObservers(state);
  72707. }
  72708. }
  72709. else {
  72710. // If the app or home buttons are ever made available
  72711. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72712. }
  72713. };
  72714. /**
  72715. * Base Url for the controller model.
  72716. */
  72717. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72718. /**
  72719. * File name for the controller model.
  72720. */
  72721. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72722. /**
  72723. * Gamepad Id prefix used to identify Daydream Controller.
  72724. */
  72725. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72726. return DaydreamController;
  72727. }(BABYLON.WebVRController));
  72728. BABYLON.DaydreamController = DaydreamController;
  72729. })(BABYLON || (BABYLON = {}));
  72730. //# sourceMappingURL=babylon.daydreamController.js.map
  72731. var BABYLON;
  72732. (function (BABYLON) {
  72733. var FollowCamera = /** @class */ (function (_super) {
  72734. __extends(FollowCamera, _super);
  72735. function FollowCamera(name, position, scene, lockedTarget) {
  72736. if (lockedTarget === void 0) { lockedTarget = null; }
  72737. var _this = _super.call(this, name, position, scene) || this;
  72738. _this.radius = 12;
  72739. _this.rotationOffset = 0;
  72740. _this.heightOffset = 4;
  72741. _this.cameraAcceleration = 0.05;
  72742. _this.maxCameraSpeed = 20;
  72743. _this.lockedTarget = lockedTarget;
  72744. return _this;
  72745. }
  72746. FollowCamera.prototype.getRadians = function (degrees) {
  72747. return degrees * Math.PI / 180;
  72748. };
  72749. FollowCamera.prototype.follow = function (cameraTarget) {
  72750. if (!cameraTarget)
  72751. return;
  72752. var yRotation;
  72753. if (cameraTarget.rotationQuaternion) {
  72754. var rotMatrix = new BABYLON.Matrix();
  72755. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72756. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72757. }
  72758. else {
  72759. yRotation = cameraTarget.rotation.y;
  72760. }
  72761. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72762. var targetPosition = cameraTarget.getAbsolutePosition();
  72763. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72764. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72765. var dx = targetX - this.position.x;
  72766. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72767. var dz = (targetZ) - this.position.z;
  72768. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72769. var vy = dy * this.cameraAcceleration;
  72770. var vz = dz * this.cameraAcceleration * 2;
  72771. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72772. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72773. }
  72774. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72775. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72776. }
  72777. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72778. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72779. }
  72780. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72781. this.setTarget(targetPosition);
  72782. };
  72783. FollowCamera.prototype._checkInputs = function () {
  72784. _super.prototype._checkInputs.call(this);
  72785. if (this.lockedTarget) {
  72786. this.follow(this.lockedTarget);
  72787. }
  72788. };
  72789. FollowCamera.prototype.getClassName = function () {
  72790. return "FollowCamera";
  72791. };
  72792. __decorate([
  72793. BABYLON.serialize()
  72794. ], FollowCamera.prototype, "radius", void 0);
  72795. __decorate([
  72796. BABYLON.serialize()
  72797. ], FollowCamera.prototype, "rotationOffset", void 0);
  72798. __decorate([
  72799. BABYLON.serialize()
  72800. ], FollowCamera.prototype, "heightOffset", void 0);
  72801. __decorate([
  72802. BABYLON.serialize()
  72803. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72804. __decorate([
  72805. BABYLON.serialize()
  72806. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72807. __decorate([
  72808. BABYLON.serializeAsMeshReference("lockedTargetId")
  72809. ], FollowCamera.prototype, "lockedTarget", void 0);
  72810. return FollowCamera;
  72811. }(BABYLON.TargetCamera));
  72812. BABYLON.FollowCamera = FollowCamera;
  72813. var ArcFollowCamera = /** @class */ (function (_super) {
  72814. __extends(ArcFollowCamera, _super);
  72815. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72816. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72817. _this.alpha = alpha;
  72818. _this.beta = beta;
  72819. _this.radius = radius;
  72820. _this.target = target;
  72821. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72822. _this.follow();
  72823. return _this;
  72824. }
  72825. ArcFollowCamera.prototype.follow = function () {
  72826. if (!this.target) {
  72827. return;
  72828. }
  72829. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72830. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72831. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72832. var targetPosition = this.target.getAbsolutePosition();
  72833. this.position = targetPosition.add(this._cartesianCoordinates);
  72834. this.setTarget(targetPosition);
  72835. };
  72836. ArcFollowCamera.prototype._checkInputs = function () {
  72837. _super.prototype._checkInputs.call(this);
  72838. this.follow();
  72839. };
  72840. ArcFollowCamera.prototype.getClassName = function () {
  72841. return "ArcFollowCamera";
  72842. };
  72843. return ArcFollowCamera;
  72844. }(BABYLON.TargetCamera));
  72845. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72846. })(BABYLON || (BABYLON = {}));
  72847. //# sourceMappingURL=babylon.followCamera.js.map
  72848. var BABYLON;
  72849. (function (BABYLON) {
  72850. // We're mainly based on the logic defined into the FreeCamera code
  72851. var UniversalCamera = /** @class */ (function (_super) {
  72852. __extends(UniversalCamera, _super);
  72853. //-- end properties for backward compatibility for inputs
  72854. function UniversalCamera(name, position, scene) {
  72855. var _this = _super.call(this, name, position, scene) || this;
  72856. _this.inputs.addGamepad();
  72857. return _this;
  72858. }
  72859. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72860. //-- Begin properties for backward compatibility for inputs
  72861. get: function () {
  72862. var gamepad = this.inputs.attached["gamepad"];
  72863. if (gamepad)
  72864. return gamepad.gamepadAngularSensibility;
  72865. return 0;
  72866. },
  72867. set: function (value) {
  72868. var gamepad = this.inputs.attached["gamepad"];
  72869. if (gamepad)
  72870. gamepad.gamepadAngularSensibility = value;
  72871. },
  72872. enumerable: true,
  72873. configurable: true
  72874. });
  72875. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72876. get: function () {
  72877. var gamepad = this.inputs.attached["gamepad"];
  72878. if (gamepad)
  72879. return gamepad.gamepadMoveSensibility;
  72880. return 0;
  72881. },
  72882. set: function (value) {
  72883. var gamepad = this.inputs.attached["gamepad"];
  72884. if (gamepad)
  72885. gamepad.gamepadMoveSensibility = value;
  72886. },
  72887. enumerable: true,
  72888. configurable: true
  72889. });
  72890. UniversalCamera.prototype.getClassName = function () {
  72891. return "UniversalCamera";
  72892. };
  72893. return UniversalCamera;
  72894. }(BABYLON.TouchCamera));
  72895. BABYLON.UniversalCamera = UniversalCamera;
  72896. })(BABYLON || (BABYLON = {}));
  72897. //# sourceMappingURL=babylon.universalCamera.js.map
  72898. var BABYLON;
  72899. (function (BABYLON) {
  72900. // We're mainly based on the logic defined into the FreeCamera code
  72901. var GamepadCamera = /** @class */ (function (_super) {
  72902. __extends(GamepadCamera, _super);
  72903. //-- end properties for backward compatibility for inputs
  72904. function GamepadCamera(name, position, scene) {
  72905. return _super.call(this, name, position, scene) || this;
  72906. }
  72907. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72908. //-- Begin properties for backward compatibility for inputs
  72909. get: function () {
  72910. var gamepad = this.inputs.attached["gamepad"];
  72911. if (gamepad)
  72912. return gamepad.gamepadAngularSensibility;
  72913. return 0;
  72914. },
  72915. set: function (value) {
  72916. var gamepad = this.inputs.attached["gamepad"];
  72917. if (gamepad)
  72918. gamepad.gamepadAngularSensibility = value;
  72919. },
  72920. enumerable: true,
  72921. configurable: true
  72922. });
  72923. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72924. get: function () {
  72925. var gamepad = this.inputs.attached["gamepad"];
  72926. if (gamepad)
  72927. return gamepad.gamepadMoveSensibility;
  72928. return 0;
  72929. },
  72930. set: function (value) {
  72931. var gamepad = this.inputs.attached["gamepad"];
  72932. if (gamepad)
  72933. gamepad.gamepadMoveSensibility = value;
  72934. },
  72935. enumerable: true,
  72936. configurable: true
  72937. });
  72938. GamepadCamera.prototype.getClassName = function () {
  72939. return "GamepadCamera";
  72940. };
  72941. return GamepadCamera;
  72942. }(BABYLON.UniversalCamera));
  72943. BABYLON.GamepadCamera = GamepadCamera;
  72944. })(BABYLON || (BABYLON = {}));
  72945. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72946. var BABYLON;
  72947. (function (BABYLON) {
  72948. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72949. function PostProcessRenderPipelineManager() {
  72950. this._renderPipelines = {};
  72951. }
  72952. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72953. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72954. };
  72955. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72956. if (unique === void 0) { unique = false; }
  72957. var renderPipeline = this._renderPipelines[renderPipelineName];
  72958. if (!renderPipeline) {
  72959. return;
  72960. }
  72961. renderPipeline._attachCameras(cameras, unique);
  72962. };
  72963. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72964. var renderPipeline = this._renderPipelines[renderPipelineName];
  72965. if (!renderPipeline) {
  72966. return;
  72967. }
  72968. renderPipeline._detachCameras(cameras);
  72969. };
  72970. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72971. var renderPipeline = this._renderPipelines[renderPipelineName];
  72972. if (!renderPipeline) {
  72973. return;
  72974. }
  72975. renderPipeline._enableEffect(renderEffectName, cameras);
  72976. };
  72977. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72978. var renderPipeline = this._renderPipelines[renderPipelineName];
  72979. if (!renderPipeline) {
  72980. return;
  72981. }
  72982. renderPipeline._disableEffect(renderEffectName, cameras);
  72983. };
  72984. PostProcessRenderPipelineManager.prototype.update = function () {
  72985. for (var renderPipelineName in this._renderPipelines) {
  72986. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72987. var pipeline = this._renderPipelines[renderPipelineName];
  72988. if (!pipeline.isSupported) {
  72989. pipeline.dispose();
  72990. delete this._renderPipelines[renderPipelineName];
  72991. }
  72992. else {
  72993. pipeline._update();
  72994. }
  72995. }
  72996. }
  72997. };
  72998. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72999. for (var renderPipelineName in this._renderPipelines) {
  73000. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73001. var pipeline = this._renderPipelines[renderPipelineName];
  73002. pipeline._rebuild();
  73003. }
  73004. }
  73005. };
  73006. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73007. for (var renderPipelineName in this._renderPipelines) {
  73008. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73009. var pipeline = this._renderPipelines[renderPipelineName];
  73010. pipeline.dispose();
  73011. }
  73012. }
  73013. };
  73014. return PostProcessRenderPipelineManager;
  73015. }());
  73016. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73017. })(BABYLON || (BABYLON = {}));
  73018. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73019. var BABYLON;
  73020. (function (BABYLON) {
  73021. /**
  73022. * This represents a set of one or more post processes in Babylon.
  73023. * A post process can be used to apply a shader to a texture after it is rendered.
  73024. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73025. */
  73026. var PostProcessRenderEffect = /** @class */ (function () {
  73027. /**
  73028. * Instantiates a post process render effect.
  73029. * A post process can be used to apply a shader to a texture after it is rendered.
  73030. * @param engine The engine the effect is tied to
  73031. * @param name The name of the effect
  73032. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73033. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73034. */
  73035. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73036. this._name = name;
  73037. this._singleInstance = singleInstance || true;
  73038. this._getPostProcesses = getPostProcesses;
  73039. this._cameras = {};
  73040. this._indicesForCamera = {};
  73041. this._postProcesses = {};
  73042. }
  73043. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73044. /**
  73045. * Checks if all the post processes in the effect are supported.
  73046. */
  73047. get: function () {
  73048. for (var index in this._postProcesses) {
  73049. if (this._postProcesses.hasOwnProperty(index)) {
  73050. var pps = this._postProcesses[index];
  73051. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73052. if (!pps[ppIndex].isSupported) {
  73053. return false;
  73054. }
  73055. }
  73056. }
  73057. }
  73058. return true;
  73059. },
  73060. enumerable: true,
  73061. configurable: true
  73062. });
  73063. /**
  73064. * Updates the current state of the effect
  73065. */
  73066. PostProcessRenderEffect.prototype._update = function () {
  73067. };
  73068. /**
  73069. * Attaches the effect on cameras
  73070. * @param cameras The camera to attach to.
  73071. */
  73072. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73073. var _this = this;
  73074. var cameraKey;
  73075. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73076. if (!cams) {
  73077. return;
  73078. }
  73079. for (var i = 0; i < cams.length; i++) {
  73080. var camera = cams[i];
  73081. var cameraName = camera.name;
  73082. if (this._singleInstance) {
  73083. cameraKey = 0;
  73084. }
  73085. else {
  73086. cameraKey = cameraName;
  73087. }
  73088. if (!this._postProcesses[cameraKey]) {
  73089. var postProcess = this._getPostProcesses();
  73090. if (postProcess) {
  73091. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73092. }
  73093. }
  73094. if (!this._indicesForCamera[cameraName]) {
  73095. this._indicesForCamera[cameraName] = [];
  73096. }
  73097. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73098. var index = camera.attachPostProcess(postProcess);
  73099. _this._indicesForCamera[cameraName].push(index);
  73100. });
  73101. if (!this._cameras[cameraName]) {
  73102. this._cameras[cameraName] = camera;
  73103. }
  73104. }
  73105. };
  73106. /**
  73107. * Detatches the effect on cameras
  73108. * @param cameras The camera to detatch from.
  73109. */
  73110. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73111. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73112. if (!cams) {
  73113. return;
  73114. }
  73115. for (var i = 0; i < cams.length; i++) {
  73116. var camera = cams[i];
  73117. var cameraName = camera.name;
  73118. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73119. camera.detachPostProcess(postProcess);
  73120. });
  73121. if (this._cameras[cameraName]) {
  73122. //this._indicesForCamera.splice(index, 1);
  73123. this._cameras[cameraName] = null;
  73124. }
  73125. }
  73126. };
  73127. /**
  73128. * Enables the effect on given cameras
  73129. * @param cameras The camera to enable.
  73130. */
  73131. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73132. var _this = this;
  73133. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73134. if (!cams) {
  73135. return;
  73136. }
  73137. for (var i = 0; i < cams.length; i++) {
  73138. var camera = cams[i];
  73139. var cameraName = camera.name;
  73140. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73141. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73142. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73143. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73144. });
  73145. }
  73146. }
  73147. }
  73148. };
  73149. /**
  73150. * Disables the effect on the given cameras
  73151. * @param cameras The camera to disable.
  73152. */
  73153. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73154. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73155. if (!cams) {
  73156. return;
  73157. }
  73158. for (var i = 0; i < cams.length; i++) {
  73159. var camera = cams[i];
  73160. var cameraName = camera.name;
  73161. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73162. camera.detachPostProcess(postProcess);
  73163. });
  73164. }
  73165. };
  73166. /**
  73167. * Gets a list of the post processes contained in the effect.
  73168. * @param camera The camera to get the post processes on.
  73169. * @returns The list of the post processes in the effect.
  73170. */
  73171. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73172. if (this._singleInstance) {
  73173. return this._postProcesses[0];
  73174. }
  73175. else {
  73176. if (!camera) {
  73177. return null;
  73178. }
  73179. return this._postProcesses[camera.name];
  73180. }
  73181. };
  73182. return PostProcessRenderEffect;
  73183. }());
  73184. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73185. })(BABYLON || (BABYLON = {}));
  73186. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73187. var BABYLON;
  73188. (function (BABYLON) {
  73189. var PostProcessRenderPipeline = /** @class */ (function () {
  73190. function PostProcessRenderPipeline(engine, name) {
  73191. this.engine = engine;
  73192. this._name = name;
  73193. this._renderEffects = {};
  73194. this._renderEffectsForIsolatedPass = new Array();
  73195. this._cameras = [];
  73196. }
  73197. PostProcessRenderPipeline.prototype.getClassName = function () {
  73198. return "PostProcessRenderPipeline";
  73199. };
  73200. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73201. get: function () {
  73202. for (var renderEffectName in this._renderEffects) {
  73203. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73204. if (!this._renderEffects[renderEffectName].isSupported) {
  73205. return false;
  73206. }
  73207. }
  73208. }
  73209. return true;
  73210. },
  73211. enumerable: true,
  73212. configurable: true
  73213. });
  73214. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73215. this._renderEffects[renderEffect._name] = renderEffect;
  73216. };
  73217. // private
  73218. PostProcessRenderPipeline.prototype._rebuild = function () {
  73219. };
  73220. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73221. var renderEffects = this._renderEffects[renderEffectName];
  73222. if (!renderEffects) {
  73223. return;
  73224. }
  73225. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73226. };
  73227. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73228. var renderEffects = this._renderEffects[renderEffectName];
  73229. if (!renderEffects) {
  73230. return;
  73231. }
  73232. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73233. };
  73234. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73235. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73236. if (!cams) {
  73237. return;
  73238. }
  73239. var indicesToDelete = [];
  73240. var i;
  73241. for (i = 0; i < cams.length; i++) {
  73242. var camera = cams[i];
  73243. var cameraName = camera.name;
  73244. if (this._cameras.indexOf(camera) === -1) {
  73245. this._cameras[cameraName] = camera;
  73246. }
  73247. else if (unique) {
  73248. indicesToDelete.push(i);
  73249. }
  73250. }
  73251. for (i = 0; i < indicesToDelete.length; i++) {
  73252. cameras.splice(indicesToDelete[i], 1);
  73253. }
  73254. for (var renderEffectName in this._renderEffects) {
  73255. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73256. this._renderEffects[renderEffectName]._attachCameras(cams);
  73257. }
  73258. }
  73259. };
  73260. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73261. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73262. if (!cams) {
  73263. return;
  73264. }
  73265. for (var renderEffectName in this._renderEffects) {
  73266. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73267. this._renderEffects[renderEffectName]._detachCameras(cams);
  73268. }
  73269. }
  73270. for (var i = 0; i < cams.length; i++) {
  73271. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73272. }
  73273. };
  73274. PostProcessRenderPipeline.prototype._update = function () {
  73275. for (var renderEffectName in this._renderEffects) {
  73276. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73277. this._renderEffects[renderEffectName]._update();
  73278. }
  73279. }
  73280. for (var i = 0; i < this._cameras.length; i++) {
  73281. var cameraName = this._cameras[i].name;
  73282. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73283. this._renderEffectsForIsolatedPass[cameraName]._update();
  73284. }
  73285. }
  73286. };
  73287. PostProcessRenderPipeline.prototype._reset = function () {
  73288. this._renderEffects = {};
  73289. this._renderEffectsForIsolatedPass = new Array();
  73290. };
  73291. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73292. // 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)
  73293. var effectKeys = Object.keys(this._renderEffects);
  73294. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73295. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73296. if (postProcesses) {
  73297. postProcesses[0].samples = sampleCount;
  73298. return true;
  73299. }
  73300. }
  73301. return false;
  73302. };
  73303. PostProcessRenderPipeline.prototype.dispose = function () {
  73304. // Must be implemented by children
  73305. };
  73306. __decorate([
  73307. BABYLON.serialize()
  73308. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73309. return PostProcessRenderPipeline;
  73310. }());
  73311. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73312. })(BABYLON || (BABYLON = {}));
  73313. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73314. var BABYLON;
  73315. (function (BABYLON) {
  73316. /**
  73317. * This represents a depth renderer in Babylon.
  73318. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73319. */
  73320. var DepthRenderer = /** @class */ (function () {
  73321. /**
  73322. * Instantiates a depth renderer
  73323. * @param scene The scene the renderer belongs to
  73324. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73325. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73326. */
  73327. function DepthRenderer(scene, type, camera) {
  73328. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73329. if (camera === void 0) { camera = null; }
  73330. var _this = this;
  73331. this._scene = scene;
  73332. this._camera = camera;
  73333. var engine = scene.getEngine();
  73334. // Render target
  73335. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73336. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73337. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73338. this._depthMap.refreshRate = 1;
  73339. this._depthMap.renderParticles = false;
  73340. this._depthMap.renderList = null;
  73341. // Camera to get depth map from to support multiple concurrent cameras
  73342. this._depthMap.activeCamera = this._camera;
  73343. this._depthMap.ignoreCameraViewport = true;
  73344. this._depthMap.useCameraPostProcesses = false;
  73345. // set default depth value to 1.0 (far away)
  73346. this._depthMap.onClearObservable.add(function (engine) {
  73347. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73348. });
  73349. // Custom render function
  73350. var renderSubMesh = function (subMesh) {
  73351. var mesh = subMesh.getRenderingMesh();
  73352. var scene = _this._scene;
  73353. var engine = scene.getEngine();
  73354. var material = subMesh.getMaterial();
  73355. if (!material) {
  73356. return;
  73357. }
  73358. // Culling and reverse (right handed system)
  73359. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73360. // Managing instances
  73361. var batch = mesh._getInstancesRenderList(subMesh._id);
  73362. if (batch.mustReturn) {
  73363. return;
  73364. }
  73365. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73366. var camera = _this._camera || scene.activeCamera;
  73367. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73368. engine.enableEffect(_this._effect);
  73369. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73370. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73371. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73372. // Alpha test
  73373. if (material && material.needAlphaTesting()) {
  73374. var alphaTexture = material.getAlphaTestTexture();
  73375. if (alphaTexture) {
  73376. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73377. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73378. }
  73379. }
  73380. // Bones
  73381. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73382. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73383. }
  73384. // Draw
  73385. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73386. }
  73387. };
  73388. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73389. var index;
  73390. if (depthOnlySubMeshes.length) {
  73391. engine.setColorWrite(false);
  73392. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73393. renderSubMesh(depthOnlySubMeshes.data[index]);
  73394. }
  73395. engine.setColorWrite(true);
  73396. }
  73397. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73398. renderSubMesh(opaqueSubMeshes.data[index]);
  73399. }
  73400. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73401. renderSubMesh(alphaTestSubMeshes.data[index]);
  73402. }
  73403. };
  73404. }
  73405. /**
  73406. * Creates the depth rendering effect and checks if the effect is ready.
  73407. * @param subMesh The submesh to be used to render the depth map of
  73408. * @param useInstances If multiple world instances should be used
  73409. * @returns if the depth renderer is ready to render the depth map
  73410. */
  73411. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73412. var material = subMesh.getMaterial();
  73413. if (material.disableDepthWrite) {
  73414. return false;
  73415. }
  73416. var defines = [];
  73417. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73418. var mesh = subMesh.getMesh();
  73419. // Alpha test
  73420. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73421. defines.push("#define ALPHATEST");
  73422. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73423. attribs.push(BABYLON.VertexBuffer.UVKind);
  73424. defines.push("#define UV1");
  73425. }
  73426. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73427. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73428. defines.push("#define UV2");
  73429. }
  73430. }
  73431. // Bones
  73432. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73433. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73434. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73435. if (mesh.numBoneInfluencers > 4) {
  73436. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73437. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73438. }
  73439. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73440. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73441. }
  73442. else {
  73443. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73444. }
  73445. // Instances
  73446. if (useInstances) {
  73447. defines.push("#define INSTANCES");
  73448. attribs.push("world0");
  73449. attribs.push("world1");
  73450. attribs.push("world2");
  73451. attribs.push("world3");
  73452. }
  73453. // Get correct effect
  73454. var join = defines.join("\n");
  73455. if (this._cachedDefines !== join) {
  73456. this._cachedDefines = join;
  73457. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73458. }
  73459. return this._effect.isReady();
  73460. };
  73461. /**
  73462. * Gets the texture which the depth map will be written to.
  73463. * @returns The depth map texture
  73464. */
  73465. DepthRenderer.prototype.getDepthMap = function () {
  73466. return this._depthMap;
  73467. };
  73468. /**
  73469. * Disposes of the depth renderer.
  73470. */
  73471. DepthRenderer.prototype.dispose = function () {
  73472. this._depthMap.dispose();
  73473. };
  73474. return DepthRenderer;
  73475. }());
  73476. BABYLON.DepthRenderer = DepthRenderer;
  73477. })(BABYLON || (BABYLON = {}));
  73478. //# sourceMappingURL=babylon.depthRenderer.js.map
  73479. var BABYLON;
  73480. (function (BABYLON) {
  73481. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73482. __extends(SSAORenderingPipeline, _super);
  73483. /**
  73484. * @constructor
  73485. * @param {string} name - The rendering pipeline name
  73486. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73487. * @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 }
  73488. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73489. */
  73490. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73491. var _this = _super.call(this, scene.getEngine(), name) || this;
  73492. // Members
  73493. /**
  73494. * The PassPostProcess id in the pipeline that contains the original scene color
  73495. */
  73496. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73497. /**
  73498. * The SSAO PostProcess id in the pipeline
  73499. */
  73500. _this.SSAORenderEffect = "SSAORenderEffect";
  73501. /**
  73502. * The horizontal blur PostProcess id in the pipeline
  73503. */
  73504. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73505. /**
  73506. * The vertical blur PostProcess id in the pipeline
  73507. */
  73508. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73509. /**
  73510. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73511. */
  73512. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73513. /**
  73514. * The output strength of the SSAO post-process. Default value is 1.0.
  73515. */
  73516. _this.totalStrength = 1.0;
  73517. /**
  73518. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73519. */
  73520. _this.radius = 0.0001;
  73521. /**
  73522. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73523. * Must not be equal to fallOff and superior to fallOff.
  73524. * Default value is 0.975
  73525. */
  73526. _this.area = 0.0075;
  73527. /**
  73528. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73529. * Must not be equal to area and inferior to area.
  73530. * Default value is 0.0
  73531. */
  73532. _this.fallOff = 0.000001;
  73533. /**
  73534. * The base color of the SSAO post-process
  73535. * The final result is "base + ssao" between [0, 1]
  73536. */
  73537. _this.base = 0.5;
  73538. _this._firstUpdate = true;
  73539. _this._scene = scene;
  73540. // Set up assets
  73541. _this._createRandomTexture();
  73542. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73543. var ssaoRatio = ratio.ssaoRatio || ratio;
  73544. var combineRatio = ratio.combineRatio || ratio;
  73545. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73546. _this._createSSAOPostProcess(ssaoRatio);
  73547. _this._createBlurPostProcess(ssaoRatio);
  73548. _this._createSSAOCombinePostProcess(combineRatio);
  73549. // Set up pipeline
  73550. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73551. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73554. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73555. // Finish
  73556. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73557. if (cameras)
  73558. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73559. return _this;
  73560. }
  73561. // Public Methods
  73562. /**
  73563. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73564. */
  73565. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73566. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73567. for (var i = 0; i < this._scene.cameras.length; i++) {
  73568. var camera = this._scene.cameras[i];
  73569. this._originalColorPostProcess.dispose(camera);
  73570. this._ssaoPostProcess.dispose(camera);
  73571. this._blurHPostProcess.dispose(camera);
  73572. this._blurVPostProcess.dispose(camera);
  73573. this._ssaoCombinePostProcess.dispose(camera);
  73574. }
  73575. this._randomTexture.dispose();
  73576. if (disableDepthRender)
  73577. this._scene.disableDepthRenderer();
  73578. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73579. _super.prototype.dispose.call(this);
  73580. };
  73581. // Private Methods
  73582. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73583. var _this = this;
  73584. var size = 16;
  73585. 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);
  73586. 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);
  73587. this._blurHPostProcess.onActivateObservable.add(function () {
  73588. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73589. _this._blurHPostProcess.kernel = size * dw;
  73590. });
  73591. this._blurVPostProcess.onActivateObservable.add(function () {
  73592. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73593. _this._blurVPostProcess.kernel = size * dw;
  73594. });
  73595. };
  73596. SSAORenderingPipeline.prototype._rebuild = function () {
  73597. this._firstUpdate = true;
  73598. _super.prototype._rebuild.call(this);
  73599. };
  73600. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73601. var _this = this;
  73602. var numSamples = 16;
  73603. var sampleSphere = [
  73604. 0.5381, 0.1856, -0.4319,
  73605. 0.1379, 0.2486, 0.4430,
  73606. 0.3371, 0.5679, -0.0057,
  73607. -0.6999, -0.0451, -0.0019,
  73608. 0.0689, -0.1598, -0.8547,
  73609. 0.0560, 0.0069, -0.1843,
  73610. -0.0146, 0.1402, 0.0762,
  73611. 0.0100, -0.1924, -0.0344,
  73612. -0.3577, -0.5301, -0.4358,
  73613. -0.3169, 0.1063, 0.0158,
  73614. 0.0103, -0.5869, 0.0046,
  73615. -0.0897, -0.4940, 0.3287,
  73616. 0.7119, -0.0154, -0.0918,
  73617. -0.0533, 0.0596, -0.5411,
  73618. 0.0352, -0.0631, 0.5460,
  73619. -0.4776, 0.2847, -0.0271
  73620. ];
  73621. var samplesFactor = 1.0 / numSamples;
  73622. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73623. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73624. "area", "fallOff", "base", "range", "viewport"
  73625. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73626. this._ssaoPostProcess.onApply = function (effect) {
  73627. if (_this._firstUpdate) {
  73628. effect.setArray3("sampleSphere", sampleSphere);
  73629. effect.setFloat("samplesFactor", samplesFactor);
  73630. effect.setFloat("randTextureTiles", 4.0);
  73631. }
  73632. effect.setFloat("totalStrength", _this.totalStrength);
  73633. effect.setFloat("radius", _this.radius);
  73634. effect.setFloat("area", _this.area);
  73635. effect.setFloat("fallOff", _this.fallOff);
  73636. effect.setFloat("base", _this.base);
  73637. effect.setTexture("textureSampler", _this._depthTexture);
  73638. effect.setTexture("randomSampler", _this._randomTexture);
  73639. };
  73640. };
  73641. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73642. var _this = this;
  73643. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73644. this._ssaoCombinePostProcess.onApply = function (effect) {
  73645. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73646. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73647. };
  73648. };
  73649. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73650. var size = 512;
  73651. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73652. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73653. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73654. var context = this._randomTexture.getContext();
  73655. var rand = function (min, max) {
  73656. return Math.random() * (max - min) + min;
  73657. };
  73658. var randVector = BABYLON.Vector3.Zero();
  73659. for (var x = 0; x < size; x++) {
  73660. for (var y = 0; y < size; y++) {
  73661. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73662. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73663. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73664. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73665. context.fillRect(x, y, 1, 1);
  73666. }
  73667. }
  73668. this._randomTexture.update(false);
  73669. };
  73670. __decorate([
  73671. BABYLON.serialize()
  73672. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73673. __decorate([
  73674. BABYLON.serialize()
  73675. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73676. __decorate([
  73677. BABYLON.serialize()
  73678. ], SSAORenderingPipeline.prototype, "area", void 0);
  73679. __decorate([
  73680. BABYLON.serialize()
  73681. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73682. __decorate([
  73683. BABYLON.serialize()
  73684. ], SSAORenderingPipeline.prototype, "base", void 0);
  73685. return SSAORenderingPipeline;
  73686. }(BABYLON.PostProcessRenderPipeline));
  73687. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73688. })(BABYLON || (BABYLON = {}));
  73689. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73690. var BABYLON;
  73691. (function (BABYLON) {
  73692. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73693. __extends(SSAO2RenderingPipeline, _super);
  73694. /**
  73695. * @constructor
  73696. * @param {string} name - The rendering pipeline name
  73697. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73698. * @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 }
  73699. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73700. */
  73701. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73702. var _this = _super.call(this, scene.getEngine(), name) || this;
  73703. // Members
  73704. /**
  73705. * The PassPostProcess id in the pipeline that contains the original scene color
  73706. */
  73707. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73708. /**
  73709. * The SSAO PostProcess id in the pipeline
  73710. */
  73711. _this.SSAORenderEffect = "SSAORenderEffect";
  73712. /**
  73713. * The horizontal blur PostProcess id in the pipeline
  73714. */
  73715. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73716. /**
  73717. * The vertical blur PostProcess id in the pipeline
  73718. */
  73719. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73720. /**
  73721. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73722. */
  73723. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73724. /**
  73725. * The output strength of the SSAO post-process. Default value is 1.0.
  73726. */
  73727. _this.totalStrength = 1.0;
  73728. /**
  73729. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73730. */
  73731. _this.maxZ = 100.0;
  73732. /**
  73733. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73734. */
  73735. _this.minZAspect = 0.2;
  73736. /**
  73737. * Number of samples used for the SSAO calculations. Default value is 8
  73738. */
  73739. _this._samples = 8;
  73740. /**
  73741. * Are we using bilateral blur ?
  73742. */
  73743. _this._expensiveBlur = true;
  73744. /**
  73745. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73746. */
  73747. _this.radius = 2.0;
  73748. /**
  73749. * The base color of the SSAO post-process
  73750. * The final result is "base + ssao" between [0, 1]
  73751. */
  73752. _this.base = 0.1;
  73753. _this._firstUpdate = true;
  73754. _this._scene = scene;
  73755. _this._ratio = ratio;
  73756. if (!_this.isSupported) {
  73757. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73758. return _this;
  73759. }
  73760. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73761. var blurRatio = _this._ratio.blurRatio || ratio;
  73762. // Set up assets
  73763. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73764. _this._createRandomTexture();
  73765. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73766. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73767. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73768. _this._createSSAOPostProcess(1.0);
  73769. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73770. _this._createSSAOCombinePostProcess(blurRatio);
  73771. // Set up pipeline
  73772. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73773. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73774. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73775. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73776. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73777. // Finish
  73778. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73779. if (cameras)
  73780. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73781. return _this;
  73782. }
  73783. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73784. get: function () {
  73785. return this._samples;
  73786. },
  73787. set: function (n) {
  73788. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73789. this._samples = n;
  73790. this._sampleSphere = this._generateHemisphere();
  73791. this._firstUpdate = true;
  73792. },
  73793. enumerable: true,
  73794. configurable: true
  73795. });
  73796. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73797. get: function () {
  73798. return this._expensiveBlur;
  73799. },
  73800. set: function (b) {
  73801. 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"]);
  73802. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73803. this._expensiveBlur = b;
  73804. this._firstUpdate = true;
  73805. },
  73806. enumerable: true,
  73807. configurable: true
  73808. });
  73809. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73810. /**
  73811. * Support test.
  73812. */
  73813. get: function () {
  73814. var engine = BABYLON.Engine.LastCreatedEngine;
  73815. if (!engine) {
  73816. return false;
  73817. }
  73818. return engine.getCaps().drawBuffersExtension;
  73819. },
  73820. enumerable: true,
  73821. configurable: true
  73822. });
  73823. // Public Methods
  73824. /**
  73825. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73826. */
  73827. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73828. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73829. for (var i = 0; i < this._scene.cameras.length; i++) {
  73830. var camera = this._scene.cameras[i];
  73831. this._originalColorPostProcess.dispose(camera);
  73832. this._ssaoPostProcess.dispose(camera);
  73833. this._blurHPostProcess.dispose(camera);
  73834. this._blurVPostProcess.dispose(camera);
  73835. this._ssaoCombinePostProcess.dispose(camera);
  73836. }
  73837. this._randomTexture.dispose();
  73838. if (disableGeometryBufferRenderer)
  73839. this._scene.disableGeometryBufferRenderer();
  73840. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73841. _super.prototype.dispose.call(this);
  73842. };
  73843. // Private Methods
  73844. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73845. var _this = this;
  73846. this._samplerOffsets = [];
  73847. var expensive = this.expensiveBlur;
  73848. for (var i = -8; i < 8; i++) {
  73849. this._samplerOffsets.push(i * 2 + 0.5);
  73850. }
  73851. 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");
  73852. this._blurHPostProcess.onApply = function (effect) {
  73853. if (!_this._scene.activeCamera) {
  73854. return;
  73855. }
  73856. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73857. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73858. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73859. effect.setFloat("radius", _this.radius);
  73860. effect.setTexture("depthSampler", _this._depthTexture);
  73861. if (_this._firstUpdate) {
  73862. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73863. }
  73864. };
  73865. 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");
  73866. this._blurVPostProcess.onApply = function (effect) {
  73867. if (!_this._scene.activeCamera) {
  73868. return;
  73869. }
  73870. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73871. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73872. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73873. effect.setFloat("radius", _this.radius);
  73874. effect.setTexture("depthSampler", _this._depthTexture);
  73875. if (_this._firstUpdate) {
  73876. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73877. _this._firstUpdate = false;
  73878. }
  73879. };
  73880. };
  73881. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73882. this._firstUpdate = true;
  73883. _super.prototype._rebuild.call(this);
  73884. };
  73885. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73886. var numSamples = this.samples;
  73887. var result = [];
  73888. var vector, scale;
  73889. var rand = function (min, max) {
  73890. return Math.random() * (max - min) + min;
  73891. };
  73892. var i = 0;
  73893. while (i < numSamples) {
  73894. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73895. vector.normalize();
  73896. scale = i / numSamples;
  73897. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73898. vector.scaleInPlace(scale);
  73899. result.push(vector.x, vector.y, vector.z);
  73900. i++;
  73901. }
  73902. return result;
  73903. };
  73904. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73905. var _this = this;
  73906. var numSamples = this.samples;
  73907. this._sampleSphere = this._generateHemisphere();
  73908. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73909. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73910. "base", "range", "projection", "near", "far", "texelSize",
  73911. "xViewport", "yViewport", "maxZ", "minZAspect"
  73912. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73913. this._ssaoPostProcess.onApply = function (effect) {
  73914. if (_this._firstUpdate) {
  73915. effect.setArray3("sampleSphere", _this._sampleSphere);
  73916. effect.setFloat("randTextureTiles", 4.0);
  73917. }
  73918. if (!_this._scene.activeCamera) {
  73919. return;
  73920. }
  73921. effect.setFloat("samplesFactor", 1 / _this.samples);
  73922. effect.setFloat("totalStrength", _this.totalStrength);
  73923. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73924. effect.setFloat("radius", _this.radius);
  73925. effect.setFloat("maxZ", _this.maxZ);
  73926. effect.setFloat("minZAspect", _this.minZAspect);
  73927. effect.setFloat("base", _this.base);
  73928. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73929. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73930. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73931. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73932. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73933. effect.setTexture("textureSampler", _this._depthTexture);
  73934. effect.setTexture("normalSampler", _this._normalTexture);
  73935. effect.setTexture("randomSampler", _this._randomTexture);
  73936. };
  73937. };
  73938. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73939. var _this = this;
  73940. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73941. this._ssaoCombinePostProcess.onApply = function (effect) {
  73942. var viewport = _this._scene.activeCamera.viewport;
  73943. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73944. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73945. };
  73946. };
  73947. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73948. var size = 512;
  73949. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73950. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73951. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73952. var context = this._randomTexture.getContext();
  73953. var rand = function (min, max) {
  73954. return Math.random() * (max - min) + min;
  73955. };
  73956. var randVector = BABYLON.Vector3.Zero();
  73957. for (var x = 0; x < size; x++) {
  73958. for (var y = 0; y < size; y++) {
  73959. randVector.x = rand(0.0, 1.0);
  73960. randVector.y = rand(0.0, 1.0);
  73961. randVector.z = 0.0;
  73962. randVector.normalize();
  73963. randVector.scaleInPlace(255);
  73964. randVector.x = Math.floor(randVector.x);
  73965. randVector.y = Math.floor(randVector.y);
  73966. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73967. context.fillRect(x, y, 1, 1);
  73968. }
  73969. }
  73970. this._randomTexture.update(false);
  73971. };
  73972. /**
  73973. * Serialize the rendering pipeline (Used when exporting)
  73974. * @returns the serialized object
  73975. */
  73976. SSAO2RenderingPipeline.prototype.serialize = function () {
  73977. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73978. serializationObject.customType = "SSAO2RenderingPipeline";
  73979. return serializationObject;
  73980. };
  73981. /**
  73982. * Parse the serialized pipeline
  73983. * @param source Source pipeline.
  73984. * @param scene The scene to load the pipeline to.
  73985. * @param rootUrl The URL of the serialized pipeline.
  73986. * @returns An instantiated pipeline from the serialized object.
  73987. */
  73988. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73989. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73990. };
  73991. __decorate([
  73992. BABYLON.serialize()
  73993. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73994. __decorate([
  73995. BABYLON.serialize()
  73996. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73997. __decorate([
  73998. BABYLON.serialize()
  73999. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74000. __decorate([
  74001. BABYLON.serialize("samples")
  74002. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74003. __decorate([
  74004. BABYLON.serialize()
  74005. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74006. __decorate([
  74007. BABYLON.serialize("expensiveBlur")
  74008. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74009. __decorate([
  74010. BABYLON.serialize()
  74011. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74012. __decorate([
  74013. BABYLON.serialize()
  74014. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74015. return SSAO2RenderingPipeline;
  74016. }(BABYLON.PostProcessRenderPipeline));
  74017. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74018. })(BABYLON || (BABYLON = {}));
  74019. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74020. // BABYLON.JS Chromatic Aberration GLSL Shader
  74021. // Author: Olivier Guyot
  74022. // Separates very slightly R, G and B colors on the edges of the screen
  74023. // Inspired by Francois Tarlier & Martins Upitis
  74024. var BABYLON;
  74025. (function (BABYLON) {
  74026. var LensRenderingPipeline = /** @class */ (function (_super) {
  74027. __extends(LensRenderingPipeline, _super);
  74028. /**
  74029. * @constructor
  74030. *
  74031. * Effect parameters are as follow:
  74032. * {
  74033. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74034. * edge_blur: number; // from 0 to x (1 for realism)
  74035. * distortion: number; // from 0 to x (1 for realism)
  74036. * grain_amount: number; // from 0 to 1
  74037. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74038. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74039. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74040. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74041. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74042. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74043. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74044. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74045. * }
  74046. * Note: if an effect parameter is unset, effect is disabled
  74047. *
  74048. * @param {string} name - The rendering pipeline name
  74049. * @param {object} parameters - An object containing all parameters (see above)
  74050. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74051. * @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)
  74052. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74053. */
  74054. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74055. if (ratio === void 0) { ratio = 1.0; }
  74056. var _this = _super.call(this, scene.getEngine(), name) || this;
  74057. // Lens effects can be of the following:
  74058. // - chromatic aberration (slight shift of RGB colors)
  74059. // - blur on the edge of the lens
  74060. // - lens distortion
  74061. // - depth-of-field blur & highlights enhancing
  74062. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74063. // - grain effect (noise or custom texture)
  74064. // Two additional texture samplers are needed:
  74065. // - depth map (for depth-of-field)
  74066. // - grain texture
  74067. /**
  74068. * The chromatic aberration PostProcess id in the pipeline
  74069. */
  74070. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74071. /**
  74072. * The highlights enhancing PostProcess id in the pipeline
  74073. */
  74074. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74075. /**
  74076. * The depth-of-field PostProcess id in the pipeline
  74077. */
  74078. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74079. _this._scene = scene;
  74080. // Fetch texture samplers
  74081. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74082. if (parameters.grain_texture) {
  74083. _this._grainTexture = parameters.grain_texture;
  74084. }
  74085. else {
  74086. _this._createGrainTexture();
  74087. }
  74088. // save parameters
  74089. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74090. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74091. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74092. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74093. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74094. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74095. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74096. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74097. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74098. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74099. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74100. // Create effects
  74101. _this._createChromaticAberrationPostProcess(ratio);
  74102. _this._createHighlightsPostProcess(ratio);
  74103. _this._createDepthOfFieldPostProcess(ratio / 4);
  74104. // Set up pipeline
  74105. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74106. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74107. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74108. if (_this._highlightsGain === -1) {
  74109. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74110. }
  74111. // Finish
  74112. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74113. if (cameras) {
  74114. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74115. }
  74116. return _this;
  74117. }
  74118. // public methods (self explanatory)
  74119. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74120. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74121. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74122. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74123. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74124. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74125. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74126. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74127. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74128. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74129. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74130. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74131. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74132. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74133. };
  74134. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74135. this._highlightsPostProcess.updateEffect();
  74136. };
  74137. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74138. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74139. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74140. this._highlightsGain = amount;
  74141. };
  74142. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74143. if (this._highlightsGain === -1) {
  74144. this._highlightsGain = 1.0;
  74145. }
  74146. this._highlightsThreshold = amount;
  74147. };
  74148. LensRenderingPipeline.prototype.disableHighlights = function () {
  74149. this._highlightsGain = -1;
  74150. };
  74151. /**
  74152. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74153. */
  74154. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74155. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74156. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74157. this._chromaticAberrationPostProcess = null;
  74158. this._highlightsPostProcess = null;
  74159. this._depthOfFieldPostProcess = null;
  74160. this._grainTexture.dispose();
  74161. if (disableDepthRender)
  74162. this._scene.disableDepthRenderer();
  74163. };
  74164. // colors shifting and distortion
  74165. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74166. var _this = this;
  74167. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74168. [], // samplers
  74169. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74170. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74171. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74172. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74173. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74174. effect.setFloat('radialIntensity', 1);
  74175. effect.setFloat2('direction', 17, 17);
  74176. effect.setFloat2('centerPosition', 0.5, 0.5);
  74177. };
  74178. };
  74179. // highlights enhancing
  74180. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74181. var _this = this;
  74182. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74183. [], // samplers
  74184. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74185. this._highlightsPostProcess.onApply = function (effect) {
  74186. effect.setFloat('gain', _this._highlightsGain);
  74187. effect.setFloat('threshold', _this._highlightsThreshold);
  74188. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74189. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74190. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74191. };
  74192. };
  74193. // colors shifting and distortion
  74194. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74195. var _this = this;
  74196. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74197. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74198. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74199. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74200. this._depthOfFieldPostProcess.onApply = function (effect) {
  74201. effect.setTexture("depthSampler", _this._depthTexture);
  74202. effect.setTexture("grainSampler", _this._grainTexture);
  74203. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74204. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74205. effect.setFloat('grain_amount', _this._grainAmount);
  74206. effect.setBool('blur_noise', _this._blurNoise);
  74207. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74208. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74209. effect.setFloat('distortion', _this._distortion);
  74210. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74211. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74212. effect.setFloat('aperture', _this._dofAperture);
  74213. effect.setFloat('darken', _this._dofDarken);
  74214. effect.setFloat('edge_blur', _this._edgeBlur);
  74215. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74216. if (_this._scene.activeCamera) {
  74217. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74218. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74219. }
  74220. };
  74221. };
  74222. // creates a black and white random noise texture, 512x512
  74223. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74224. var size = 512;
  74225. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74226. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74227. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74228. var context = this._grainTexture.getContext();
  74229. var rand = function (min, max) {
  74230. return Math.random() * (max - min) + min;
  74231. };
  74232. var value;
  74233. for (var x = 0; x < size; x++) {
  74234. for (var y = 0; y < size; y++) {
  74235. value = Math.floor(rand(0.42, 0.58) * 255);
  74236. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74237. context.fillRect(x, y, 1, 1);
  74238. }
  74239. }
  74240. this._grainTexture.update(false);
  74241. };
  74242. return LensRenderingPipeline;
  74243. }(BABYLON.PostProcessRenderPipeline));
  74244. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74245. })(BABYLON || (BABYLON = {}));
  74246. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74247. var BABYLON;
  74248. (function (BABYLON) {
  74249. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74250. __extends(StandardRenderingPipeline, _super);
  74251. /**
  74252. * @constructor
  74253. * @param {string} name - The rendering pipeline name
  74254. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74255. * @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)
  74256. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74257. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74258. */
  74259. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74260. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74261. var _this = _super.call(this, scene.getEngine(), name) || this;
  74262. _this.downSampleX4PostProcess = null;
  74263. _this.brightPassPostProcess = null;
  74264. _this.blurHPostProcesses = [];
  74265. _this.blurVPostProcesses = [];
  74266. _this.textureAdderPostProcess = null;
  74267. _this.volumetricLightPostProcess = null;
  74268. _this.volumetricLightSmoothXPostProcess = null;
  74269. _this.volumetricLightSmoothYPostProcess = null;
  74270. _this.volumetricLightMergePostProces = null;
  74271. _this.volumetricLightFinalPostProcess = null;
  74272. _this.luminancePostProcess = null;
  74273. _this.luminanceDownSamplePostProcesses = [];
  74274. _this.hdrPostProcess = null;
  74275. _this.textureAdderFinalPostProcess = null;
  74276. _this.lensFlareFinalPostProcess = null;
  74277. _this.hdrFinalPostProcess = null;
  74278. _this.lensFlarePostProcess = null;
  74279. _this.lensFlareComposePostProcess = null;
  74280. _this.motionBlurPostProcess = null;
  74281. _this.depthOfFieldPostProcess = null;
  74282. // Values
  74283. _this.brightThreshold = 1.0;
  74284. _this.blurWidth = 512.0;
  74285. _this.horizontalBlur = false;
  74286. _this.exposure = 1.0;
  74287. _this.lensTexture = null;
  74288. _this.volumetricLightCoefficient = 0.2;
  74289. _this.volumetricLightPower = 4.0;
  74290. _this.volumetricLightBlurScale = 64.0;
  74291. _this.sourceLight = null;
  74292. _this.hdrMinimumLuminance = 1.0;
  74293. _this.hdrDecreaseRate = 0.5;
  74294. _this.hdrIncreaseRate = 0.5;
  74295. _this.lensColorTexture = null;
  74296. _this.lensFlareStrength = 20.0;
  74297. _this.lensFlareGhostDispersal = 1.4;
  74298. _this.lensFlareHaloWidth = 0.7;
  74299. _this.lensFlareDistortionStrength = 16.0;
  74300. _this.lensStarTexture = null;
  74301. _this.lensFlareDirtTexture = null;
  74302. _this.depthOfFieldDistance = 10.0;
  74303. _this.depthOfFieldBlurWidth = 64.0;
  74304. _this.motionStrength = 1.0;
  74305. // IAnimatable
  74306. _this.animations = [];
  74307. _this._currentDepthOfFieldSource = null;
  74308. _this._hdrCurrentLuminance = 1.0;
  74309. // Getters and setters
  74310. _this._bloomEnabled = true;
  74311. _this._depthOfFieldEnabled = false;
  74312. _this._vlsEnabled = false;
  74313. _this._lensFlareEnabled = false;
  74314. _this._hdrEnabled = false;
  74315. _this._motionBlurEnabled = false;
  74316. _this._motionBlurSamples = 64.0;
  74317. _this._volumetricLightStepsCount = 50.0;
  74318. _this._cameras = cameras || [];
  74319. // Initialize
  74320. _this._scene = scene;
  74321. _this._basePostProcess = originalPostProcess;
  74322. _this._ratio = ratio;
  74323. // Misc
  74324. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74325. // Finish
  74326. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74327. _this._buildPipeline();
  74328. return _this;
  74329. }
  74330. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74331. get: function () {
  74332. return this._bloomEnabled;
  74333. },
  74334. set: function (enabled) {
  74335. if (this._bloomEnabled === enabled) {
  74336. return;
  74337. }
  74338. this._bloomEnabled = enabled;
  74339. this._buildPipeline();
  74340. },
  74341. enumerable: true,
  74342. configurable: true
  74343. });
  74344. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74345. get: function () {
  74346. return this._depthOfFieldEnabled;
  74347. },
  74348. set: function (enabled) {
  74349. if (this._depthOfFieldEnabled === enabled) {
  74350. return;
  74351. }
  74352. this._depthOfFieldEnabled = enabled;
  74353. this._buildPipeline();
  74354. },
  74355. enumerable: true,
  74356. configurable: true
  74357. });
  74358. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74359. get: function () {
  74360. return this._lensFlareEnabled;
  74361. },
  74362. set: function (enabled) {
  74363. if (this._lensFlareEnabled === enabled) {
  74364. return;
  74365. }
  74366. this._lensFlareEnabled = enabled;
  74367. this._buildPipeline();
  74368. },
  74369. enumerable: true,
  74370. configurable: true
  74371. });
  74372. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74373. get: function () {
  74374. return this._hdrEnabled;
  74375. },
  74376. set: function (enabled) {
  74377. if (this._hdrEnabled === enabled) {
  74378. return;
  74379. }
  74380. this._hdrEnabled = enabled;
  74381. this._buildPipeline();
  74382. },
  74383. enumerable: true,
  74384. configurable: true
  74385. });
  74386. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74387. get: function () {
  74388. return this._vlsEnabled;
  74389. },
  74390. set: function (enabled) {
  74391. if (this._vlsEnabled === enabled) {
  74392. return;
  74393. }
  74394. if (enabled) {
  74395. var geometry = this._scene.enableGeometryBufferRenderer();
  74396. if (!geometry) {
  74397. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74398. return;
  74399. }
  74400. }
  74401. this._vlsEnabled = enabled;
  74402. this._buildPipeline();
  74403. },
  74404. enumerable: true,
  74405. configurable: true
  74406. });
  74407. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74408. get: function () {
  74409. return this._motionBlurEnabled;
  74410. },
  74411. set: function (enabled) {
  74412. if (this._motionBlurEnabled === enabled) {
  74413. return;
  74414. }
  74415. this._motionBlurEnabled = enabled;
  74416. this._buildPipeline();
  74417. },
  74418. enumerable: true,
  74419. configurable: true
  74420. });
  74421. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74422. get: function () {
  74423. return this._volumetricLightStepsCount;
  74424. },
  74425. set: function (count) {
  74426. if (this.volumetricLightPostProcess) {
  74427. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74428. }
  74429. this._volumetricLightStepsCount = count;
  74430. },
  74431. enumerable: true,
  74432. configurable: true
  74433. });
  74434. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74435. get: function () {
  74436. return this._motionBlurSamples;
  74437. },
  74438. set: function (samples) {
  74439. if (this.motionBlurPostProcess) {
  74440. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74441. }
  74442. this._motionBlurSamples = samples;
  74443. },
  74444. enumerable: true,
  74445. configurable: true
  74446. });
  74447. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74448. var _this = this;
  74449. var ratio = this._ratio;
  74450. var scene = this._scene;
  74451. this._disposePostProcesses();
  74452. this._reset();
  74453. // Create pass post-process
  74454. if (!this._basePostProcess) {
  74455. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74456. this.originalPostProcess.onApply = function (effect) {
  74457. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74458. };
  74459. }
  74460. else {
  74461. this.originalPostProcess = this._basePostProcess;
  74462. }
  74463. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74464. this._currentDepthOfFieldSource = this.originalPostProcess;
  74465. if (this._bloomEnabled) {
  74466. // Create down sample X4 post-process
  74467. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74468. // Create bright pass post-process
  74469. this._createBrightPassPostProcess(scene, ratio / 2);
  74470. // Create gaussian blur post-processes (down sampling blurs)
  74471. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74472. // Create texture adder post-process
  74473. this._createTextureAdderPostProcess(scene, ratio);
  74474. // Create depth-of-field source post-process
  74475. 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);
  74476. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74477. }
  74478. if (this._vlsEnabled) {
  74479. // Create volumetric light
  74480. this._createVolumetricLightPostProcess(scene, ratio);
  74481. // Create volumetric light final post-process
  74482. 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);
  74483. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74484. }
  74485. if (this._lensFlareEnabled) {
  74486. // Create lens flare post-process
  74487. this._createLensFlarePostProcess(scene, ratio);
  74488. // Create depth-of-field source post-process post lens-flare and disable it now
  74489. 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);
  74490. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74491. }
  74492. if (this._hdrEnabled) {
  74493. // Create luminance
  74494. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74495. // Create HDR
  74496. this._createHdrPostProcess(scene, ratio);
  74497. // Create depth-of-field source post-process post hdr and disable it now
  74498. 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);
  74499. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74500. }
  74501. if (this._depthOfFieldEnabled) {
  74502. // Create gaussian blur used by depth-of-field
  74503. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74504. // Create depth-of-field post-process
  74505. this._createDepthOfFieldPostProcess(scene, ratio);
  74506. }
  74507. if (this._motionBlurEnabled) {
  74508. // Create motion blur post-process
  74509. this._createMotionBlurPostProcess(scene, ratio);
  74510. }
  74511. if (this._cameras !== null) {
  74512. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74513. }
  74514. };
  74515. // Down Sample X4 Post-Processs
  74516. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74517. var _this = this;
  74518. var downSampleX4Offsets = new Array(32);
  74519. 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);
  74520. this.downSampleX4PostProcess.onApply = function (effect) {
  74521. var id = 0;
  74522. var width = _this.downSampleX4PostProcess.width;
  74523. var height = _this.downSampleX4PostProcess.height;
  74524. for (var i = -2; i < 2; i++) {
  74525. for (var j = -2; j < 2; j++) {
  74526. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74527. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74528. id += 2;
  74529. }
  74530. }
  74531. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74532. };
  74533. // Add to pipeline
  74534. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74535. };
  74536. // Brightpass Post-Process
  74537. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74538. var _this = this;
  74539. var brightOffsets = new Array(8);
  74540. 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);
  74541. this.brightPassPostProcess.onApply = function (effect) {
  74542. var sU = (1.0 / _this.brightPassPostProcess.width);
  74543. var sV = (1.0 / _this.brightPassPostProcess.height);
  74544. brightOffsets[0] = -0.5 * sU;
  74545. brightOffsets[1] = 0.5 * sV;
  74546. brightOffsets[2] = 0.5 * sU;
  74547. brightOffsets[3] = 0.5 * sV;
  74548. brightOffsets[4] = -0.5 * sU;
  74549. brightOffsets[5] = -0.5 * sV;
  74550. brightOffsets[6] = 0.5 * sU;
  74551. brightOffsets[7] = -0.5 * sV;
  74552. effect.setArray2("dsOffsets", brightOffsets);
  74553. effect.setFloat("brightThreshold", _this.brightThreshold);
  74554. };
  74555. // Add to pipeline
  74556. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74557. };
  74558. // Create blur H&V post-processes
  74559. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74560. var _this = this;
  74561. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74562. var engine = scene.getEngine();
  74563. 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);
  74564. 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);
  74565. blurX.onActivateObservable.add(function () {
  74566. var dw = blurX.width / engine.getRenderWidth();
  74567. blurX.kernel = _this[blurWidthKey] * dw;
  74568. });
  74569. blurY.onActivateObservable.add(function () {
  74570. var dw = blurY.height / engine.getRenderHeight();
  74571. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74572. });
  74573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74574. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74575. this.blurHPostProcesses.push(blurX);
  74576. this.blurVPostProcesses.push(blurY);
  74577. };
  74578. // Create texture adder post-process
  74579. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74580. var _this = this;
  74581. 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);
  74582. this.textureAdderPostProcess.onApply = function (effect) {
  74583. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74584. effect.setTexture("lensSampler", _this.lensTexture);
  74585. effect.setFloat("exposure", _this.exposure);
  74586. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74587. };
  74588. // Add to pipeline
  74589. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74590. };
  74591. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74592. var _this = this;
  74593. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74594. geometryRenderer.enablePosition = true;
  74595. var geometry = geometryRenderer.getGBuffer();
  74596. // Base post-process
  74597. 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));
  74598. var depthValues = BABYLON.Vector2.Zero();
  74599. this.volumetricLightPostProcess.onApply = function (effect) {
  74600. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74601. var generator = _this.sourceLight.getShadowGenerator();
  74602. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74603. effect.setTexture("positionSampler", geometry.textures[2]);
  74604. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74605. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74606. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74607. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74608. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74609. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74610. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74611. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74612. effect.setVector2("depthValues", depthValues);
  74613. }
  74614. };
  74615. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74616. // Smooth
  74617. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74618. // Merge
  74619. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74620. this.volumetricLightMergePostProces.onApply = function (effect) {
  74621. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74622. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74623. };
  74624. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74625. };
  74626. // Create luminance
  74627. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74628. var _this = this;
  74629. // Create luminance
  74630. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74631. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74632. var offsets = [];
  74633. this.luminancePostProcess.onApply = function (effect) {
  74634. var sU = (1.0 / _this.luminancePostProcess.width);
  74635. var sV = (1.0 / _this.luminancePostProcess.height);
  74636. offsets[0] = -0.5 * sU;
  74637. offsets[1] = 0.5 * sV;
  74638. offsets[2] = 0.5 * sU;
  74639. offsets[3] = 0.5 * sV;
  74640. offsets[4] = -0.5 * sU;
  74641. offsets[5] = -0.5 * sV;
  74642. offsets[6] = 0.5 * sU;
  74643. offsets[7] = -0.5 * sV;
  74644. effect.setArray2("lumOffsets", offsets);
  74645. };
  74646. // Add to pipeline
  74647. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74648. // Create down sample luminance
  74649. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74650. var size = Math.pow(3, i);
  74651. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74652. if (i === 0) {
  74653. defines += "#define FINAL_DOWN_SAMPLER";
  74654. }
  74655. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74656. this.luminanceDownSamplePostProcesses.push(postProcess);
  74657. }
  74658. // Create callbacks and add effects
  74659. var lastLuminance = this.luminancePostProcess;
  74660. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74661. var downSampleOffsets = new Array(18);
  74662. pp.onApply = function (effect) {
  74663. if (!lastLuminance) {
  74664. return;
  74665. }
  74666. var id = 0;
  74667. for (var x = -1; x < 2; x++) {
  74668. for (var y = -1; y < 2; y++) {
  74669. downSampleOffsets[id] = x / lastLuminance.width;
  74670. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74671. id += 2;
  74672. }
  74673. }
  74674. effect.setArray2("dsOffsets", downSampleOffsets);
  74675. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74676. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74677. lastLuminance = _this.luminancePostProcess;
  74678. }
  74679. else {
  74680. lastLuminance = pp;
  74681. }
  74682. };
  74683. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74684. pp.onAfterRender = function (effect) {
  74685. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74686. 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);
  74687. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74688. };
  74689. }
  74690. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74691. });
  74692. };
  74693. // Create HDR post-process
  74694. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74695. var _this = this;
  74696. 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);
  74697. var outputLiminance = 1;
  74698. var time = 0;
  74699. var lastTime = 0;
  74700. this.hdrPostProcess.onApply = function (effect) {
  74701. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74702. time += scene.getEngine().getDeltaTime();
  74703. if (outputLiminance < 0) {
  74704. outputLiminance = _this._hdrCurrentLuminance;
  74705. }
  74706. else {
  74707. var dt = (lastTime - time) / 1000.0;
  74708. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74709. outputLiminance += _this.hdrDecreaseRate * dt;
  74710. }
  74711. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74712. outputLiminance -= _this.hdrIncreaseRate * dt;
  74713. }
  74714. else {
  74715. outputLiminance = _this._hdrCurrentLuminance;
  74716. }
  74717. }
  74718. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74719. effect.setFloat("averageLuminance", outputLiminance);
  74720. lastTime = time;
  74721. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74722. };
  74723. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74724. };
  74725. // Create lens flare post-process
  74726. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74727. var _this = this;
  74728. 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);
  74729. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74730. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74731. 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);
  74732. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74733. var resolution = new BABYLON.Vector2(0, 0);
  74734. // Lens flare
  74735. this.lensFlarePostProcess.onApply = function (effect) {
  74736. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74737. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74738. effect.setFloat("strength", _this.lensFlareStrength);
  74739. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74740. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74741. // Shift
  74742. resolution.x = _this.lensFlarePostProcess.width;
  74743. resolution.y = _this.lensFlarePostProcess.height;
  74744. effect.setVector2("resolution", resolution);
  74745. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74746. };
  74747. // Compose
  74748. 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);
  74749. 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);
  74750. this.lensFlareComposePostProcess.onApply = function (effect) {
  74751. if (!_this._scene.activeCamera) {
  74752. return;
  74753. }
  74754. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74755. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74756. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74757. // Lens start rotation matrix
  74758. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74759. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74760. 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));
  74761. camRot *= 4.0;
  74762. 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);
  74763. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74764. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74765. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74766. };
  74767. };
  74768. // Create depth-of-field post-process
  74769. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74770. var _this = this;
  74771. 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);
  74772. this.depthOfFieldPostProcess.onApply = function (effect) {
  74773. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74774. effect.setTexture("depthSampler", _this._getDepthTexture());
  74775. effect.setFloat("distance", _this.depthOfFieldDistance);
  74776. };
  74777. // Add to pipeline
  74778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74779. };
  74780. // Create motion blur post-process
  74781. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74782. var _this = this;
  74783. 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);
  74784. var motionScale = 0;
  74785. var prevViewProjection = BABYLON.Matrix.Identity();
  74786. var invViewProjection = BABYLON.Matrix.Identity();
  74787. var viewProjection = BABYLON.Matrix.Identity();
  74788. var screenSize = BABYLON.Vector2.Zero();
  74789. this.motionBlurPostProcess.onApply = function (effect) {
  74790. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74791. viewProjection.invertToRef(invViewProjection);
  74792. effect.setMatrix("inverseViewProjection", invViewProjection);
  74793. effect.setMatrix("prevViewProjection", prevViewProjection);
  74794. prevViewProjection = viewProjection;
  74795. screenSize.x = _this.motionBlurPostProcess.width;
  74796. screenSize.y = _this.motionBlurPostProcess.height;
  74797. effect.setVector2("screenSize", screenSize);
  74798. motionScale = scene.getEngine().getFps() / 60.0;
  74799. effect.setFloat("motionScale", motionScale);
  74800. effect.setFloat("motionStrength", _this.motionStrength);
  74801. effect.setTexture("depthSampler", _this._getDepthTexture());
  74802. };
  74803. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74804. };
  74805. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74806. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74807. var renderer = this._scene.enableGeometryBufferRenderer();
  74808. return renderer.getGBuffer().textures[0];
  74809. }
  74810. return this._scene.enableDepthRenderer().getDepthMap();
  74811. };
  74812. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74813. for (var i = 0; i < this._cameras.length; i++) {
  74814. var camera = this._cameras[i];
  74815. if (this.originalPostProcess) {
  74816. this.originalPostProcess.dispose(camera);
  74817. }
  74818. if (this.downSampleX4PostProcess) {
  74819. this.downSampleX4PostProcess.dispose(camera);
  74820. }
  74821. if (this.brightPassPostProcess) {
  74822. this.brightPassPostProcess.dispose(camera);
  74823. }
  74824. if (this.textureAdderPostProcess) {
  74825. this.textureAdderPostProcess.dispose(camera);
  74826. }
  74827. if (this.textureAdderFinalPostProcess) {
  74828. this.textureAdderFinalPostProcess.dispose(camera);
  74829. }
  74830. if (this.volumetricLightPostProcess) {
  74831. this.volumetricLightPostProcess.dispose(camera);
  74832. }
  74833. if (this.volumetricLightSmoothXPostProcess) {
  74834. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74835. }
  74836. if (this.volumetricLightSmoothYPostProcess) {
  74837. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74838. }
  74839. if (this.volumetricLightMergePostProces) {
  74840. this.volumetricLightMergePostProces.dispose(camera);
  74841. }
  74842. if (this.volumetricLightFinalPostProcess) {
  74843. this.volumetricLightFinalPostProcess.dispose(camera);
  74844. }
  74845. if (this.lensFlarePostProcess) {
  74846. this.lensFlarePostProcess.dispose(camera);
  74847. }
  74848. if (this.lensFlareComposePostProcess) {
  74849. this.lensFlareComposePostProcess.dispose(camera);
  74850. }
  74851. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74852. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74853. }
  74854. if (this.luminancePostProcess) {
  74855. this.luminancePostProcess.dispose(camera);
  74856. }
  74857. if (this.hdrPostProcess) {
  74858. this.hdrPostProcess.dispose(camera);
  74859. }
  74860. if (this.hdrFinalPostProcess) {
  74861. this.hdrFinalPostProcess.dispose(camera);
  74862. }
  74863. if (this.depthOfFieldPostProcess) {
  74864. this.depthOfFieldPostProcess.dispose(camera);
  74865. }
  74866. if (this.motionBlurPostProcess) {
  74867. this.motionBlurPostProcess.dispose(camera);
  74868. }
  74869. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74870. this.blurHPostProcesses[j].dispose(camera);
  74871. }
  74872. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74873. this.blurVPostProcesses[j].dispose(camera);
  74874. }
  74875. }
  74876. this.originalPostProcess = null;
  74877. this.downSampleX4PostProcess = null;
  74878. this.brightPassPostProcess = null;
  74879. this.textureAdderPostProcess = null;
  74880. this.textureAdderFinalPostProcess = null;
  74881. this.volumetricLightPostProcess = null;
  74882. this.volumetricLightSmoothXPostProcess = null;
  74883. this.volumetricLightSmoothYPostProcess = null;
  74884. this.volumetricLightMergePostProces = null;
  74885. this.volumetricLightFinalPostProcess = null;
  74886. this.lensFlarePostProcess = null;
  74887. this.lensFlareComposePostProcess = null;
  74888. this.luminancePostProcess = null;
  74889. this.hdrPostProcess = null;
  74890. this.hdrFinalPostProcess = null;
  74891. this.depthOfFieldPostProcess = null;
  74892. this.motionBlurPostProcess = null;
  74893. this.luminanceDownSamplePostProcesses = [];
  74894. this.blurHPostProcesses = [];
  74895. this.blurVPostProcesses = [];
  74896. };
  74897. /**
  74898. * Dispose of the pipeline and stop all post processes
  74899. */
  74900. StandardRenderingPipeline.prototype.dispose = function () {
  74901. this._disposePostProcesses();
  74902. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74903. _super.prototype.dispose.call(this);
  74904. };
  74905. /**
  74906. * Serialize the rendering pipeline (Used when exporting)
  74907. * @returns the serialized object
  74908. */
  74909. StandardRenderingPipeline.prototype.serialize = function () {
  74910. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74911. if (this.sourceLight) {
  74912. serializationObject.sourceLightId = this.sourceLight.id;
  74913. }
  74914. serializationObject.customType = "StandardRenderingPipeline";
  74915. return serializationObject;
  74916. };
  74917. /**
  74918. * Parse the serialized pipeline
  74919. * @param source Source pipeline.
  74920. * @param scene The scene to load the pipeline to.
  74921. * @param rootUrl The URL of the serialized pipeline.
  74922. * @returns An instantiated pipeline from the serialized object.
  74923. */
  74924. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74925. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74926. if (source.sourceLightId) {
  74927. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74928. }
  74929. return p;
  74930. };
  74931. // Luminance steps
  74932. StandardRenderingPipeline.LuminanceSteps = 6;
  74933. __decorate([
  74934. BABYLON.serialize()
  74935. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74936. __decorate([
  74937. BABYLON.serialize()
  74938. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74939. __decorate([
  74940. BABYLON.serialize()
  74941. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74942. __decorate([
  74943. BABYLON.serialize()
  74944. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74945. __decorate([
  74946. BABYLON.serializeAsTexture("lensTexture")
  74947. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74948. __decorate([
  74949. BABYLON.serialize()
  74950. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74951. __decorate([
  74952. BABYLON.serialize()
  74953. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74954. __decorate([
  74955. BABYLON.serialize()
  74956. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74957. __decorate([
  74958. BABYLON.serialize()
  74959. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74960. __decorate([
  74961. BABYLON.serialize()
  74962. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74963. __decorate([
  74964. BABYLON.serialize()
  74965. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74966. __decorate([
  74967. BABYLON.serializeAsTexture("lensColorTexture")
  74968. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74969. __decorate([
  74970. BABYLON.serialize()
  74971. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74972. __decorate([
  74973. BABYLON.serialize()
  74974. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74975. __decorate([
  74976. BABYLON.serialize()
  74977. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74978. __decorate([
  74979. BABYLON.serialize()
  74980. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74981. __decorate([
  74982. BABYLON.serializeAsTexture("lensStarTexture")
  74983. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74984. __decorate([
  74985. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74986. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74987. __decorate([
  74988. BABYLON.serialize()
  74989. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74990. __decorate([
  74991. BABYLON.serialize()
  74992. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74993. __decorate([
  74994. BABYLON.serialize()
  74995. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74996. __decorate([
  74997. BABYLON.serialize()
  74998. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74999. __decorate([
  75000. BABYLON.serialize()
  75001. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75002. __decorate([
  75003. BABYLON.serialize()
  75004. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75005. __decorate([
  75006. BABYLON.serialize()
  75007. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75008. __decorate([
  75009. BABYLON.serialize()
  75010. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75011. __decorate([
  75012. BABYLON.serialize()
  75013. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75014. __decorate([
  75015. BABYLON.serialize()
  75016. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75017. __decorate([
  75018. BABYLON.serialize()
  75019. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75020. __decorate([
  75021. BABYLON.serialize()
  75022. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75023. return StandardRenderingPipeline;
  75024. }(BABYLON.PostProcessRenderPipeline));
  75025. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75026. })(BABYLON || (BABYLON = {}));
  75027. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75028. var BABYLON;
  75029. (function (BABYLON) {
  75030. var FxaaPostProcess = /** @class */ (function (_super) {
  75031. __extends(FxaaPostProcess, _super);
  75032. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75033. if (camera === void 0) { camera = null; }
  75034. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75035. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75036. var defines = _this._getDefines();
  75037. _this.updateEffect(defines);
  75038. _this.onApplyObservable.add(function (effect) {
  75039. var texelSize = _this.texelSize;
  75040. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75041. });
  75042. return _this;
  75043. }
  75044. FxaaPostProcess.prototype._getDefines = function () {
  75045. var engine = this.getEngine();
  75046. if (!engine) {
  75047. return null;
  75048. }
  75049. var glInfo = engine.getGlInfo();
  75050. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75051. return "#define MALI 1\n";
  75052. }
  75053. return null;
  75054. };
  75055. return FxaaPostProcess;
  75056. }(BABYLON.PostProcess));
  75057. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75058. })(BABYLON || (BABYLON = {}));
  75059. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75060. var BABYLON;
  75061. (function (BABYLON) {
  75062. /**
  75063. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75064. */
  75065. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75066. __extends(ChromaticAberrationPostProcess, _super);
  75067. /**
  75068. * Creates a new instance ChromaticAberrationPostProcess
  75069. * @param name The name of the effect.
  75070. * @param screenWidth The width of the screen to apply the effect on.
  75071. * @param screenHeight The height of the screen to apply the effect on.
  75072. * @param options The required width/height ratio to downsize to before computing the render pass.
  75073. * @param camera The camera to apply the render pass to.
  75074. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75075. * @param engine The engine which the post process will be applied. (default: current engine)
  75076. * @param reusable If the post process can be reused on the same frame. (default: false)
  75077. * @param textureType Type of textures used when performing the post process. (default: 0)
  75078. * @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)
  75079. */
  75080. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75081. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75082. if (blockCompilation === void 0) { blockCompilation = false; }
  75083. 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;
  75084. /**
  75085. * The amount of seperation of rgb channels (default: 30)
  75086. */
  75087. _this.aberrationAmount = 30;
  75088. /**
  75089. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75090. */
  75091. _this.radialIntensity = 0;
  75092. /**
  75093. * 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))
  75094. */
  75095. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75096. /**
  75097. * 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))
  75098. */
  75099. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75100. _this.onApplyObservable.add(function (effect) {
  75101. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75102. effect.setFloat('screen_width', screenWidth);
  75103. effect.setFloat('screen_height', screenHeight);
  75104. effect.setFloat('radialIntensity', _this.radialIntensity);
  75105. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75106. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75107. });
  75108. return _this;
  75109. }
  75110. return ChromaticAberrationPostProcess;
  75111. }(BABYLON.PostProcess));
  75112. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75113. })(BABYLON || (BABYLON = {}));
  75114. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75115. var BABYLON;
  75116. (function (BABYLON) {
  75117. /**
  75118. * The GrainPostProcess adds noise to the image at mid luminance levels
  75119. */
  75120. var GrainPostProcess = /** @class */ (function (_super) {
  75121. __extends(GrainPostProcess, _super);
  75122. /**
  75123. * Creates a new instance of @see GrainPostProcess
  75124. * @param name The name of the effect.
  75125. * @param options The required width/height ratio to downsize to before computing the render pass.
  75126. * @param camera The camera to apply the render pass to.
  75127. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75128. * @param engine The engine which the post process will be applied. (default: current engine)
  75129. * @param reusable If the post process can be reused on the same frame. (default: false)
  75130. * @param textureType Type of textures used when performing the post process. (default: 0)
  75131. * @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)
  75132. */
  75133. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75134. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75135. if (blockCompilation === void 0) { blockCompilation = false; }
  75136. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75137. /**
  75138. * The intensity of the grain added (default: 30)
  75139. */
  75140. _this.intensity = 30;
  75141. /**
  75142. * If the grain should be randomized on every frame
  75143. */
  75144. _this.animated = false;
  75145. _this.onApplyObservable.add(function (effect) {
  75146. effect.setFloat('intensity', _this.intensity);
  75147. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75148. });
  75149. return _this;
  75150. }
  75151. return GrainPostProcess;
  75152. }(BABYLON.PostProcess));
  75153. BABYLON.GrainPostProcess = GrainPostProcess;
  75154. })(BABYLON || (BABYLON = {}));
  75155. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75156. var BABYLON;
  75157. (function (BABYLON) {
  75158. /**
  75159. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75160. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75161. */
  75162. var SharpenPostProcess = /** @class */ (function (_super) {
  75163. __extends(SharpenPostProcess, _super);
  75164. /**
  75165. * Creates a new instance ConvolutionPostProcess
  75166. * @param name The name of the effect.
  75167. * @param options The required width/height ratio to downsize to before computing the render pass.
  75168. * @param camera The camera to apply the render pass to.
  75169. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75170. * @param engine The engine which the post process will be applied. (default: current engine)
  75171. * @param reusable If the post process can be reused on the same frame. (default: false)
  75172. * @param textureType Type of textures used when performing the post process. (default: 0)
  75173. * @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)
  75174. */
  75175. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75176. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75177. if (blockCompilation === void 0) { blockCompilation = false; }
  75178. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75179. /**
  75180. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75181. */
  75182. _this.colorAmount = 1.0;
  75183. /**
  75184. * How much sharpness should be applied (default: 0.3)
  75185. */
  75186. _this.edgeAmount = 0.3;
  75187. _this.onApply = function (effect) {
  75188. effect.setFloat2("screenSize", _this.width, _this.height);
  75189. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75190. };
  75191. return _this;
  75192. }
  75193. return SharpenPostProcess;
  75194. }(BABYLON.PostProcess));
  75195. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75196. })(BABYLON || (BABYLON = {}));
  75197. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75198. var BABYLON;
  75199. (function (BABYLON) {
  75200. /**
  75201. * The Blur Post Process which blurs an image based on a kernel and direction.
  75202. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75203. */
  75204. var BlurPostProcess = /** @class */ (function (_super) {
  75205. __extends(BlurPostProcess, _super);
  75206. /**
  75207. * Creates a new instance BlurPostProcess
  75208. * @param name The name of the effect.
  75209. * @param direction The direction in which to blur the image.
  75210. * @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.
  75211. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75212. * @param camera The camera to apply the render pass to.
  75213. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75214. * @param engine The engine which the post process will be applied. (default: current engine)
  75215. * @param reusable If the post process can be reused on the same frame. (default: false)
  75216. * @param textureType Type of textures used when performing the post process. (default: 0)
  75217. * @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)
  75218. */
  75219. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75220. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75221. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75222. if (defines === void 0) { defines = ""; }
  75223. if (blockCompilation === void 0) { blockCompilation = false; }
  75224. 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;
  75225. _this.direction = direction;
  75226. _this.blockCompilation = blockCompilation;
  75227. _this._packedFloat = false;
  75228. _this._staticDefines = "";
  75229. _this._staticDefines = defines;
  75230. _this.onApplyObservable.add(function (effect) {
  75231. if (_this._outputTexture) {
  75232. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75233. }
  75234. else {
  75235. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75236. }
  75237. });
  75238. _this.kernel = kernel;
  75239. return _this;
  75240. }
  75241. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75242. /**
  75243. * Gets the length in pixels of the blur sample region
  75244. */
  75245. get: function () {
  75246. return this._idealKernel;
  75247. },
  75248. /**
  75249. * Sets the length in pixels of the blur sample region
  75250. */
  75251. set: function (v) {
  75252. if (this._idealKernel === v) {
  75253. return;
  75254. }
  75255. v = Math.max(v, 1);
  75256. this._idealKernel = v;
  75257. this._kernel = this._nearestBestKernel(v);
  75258. if (!this.blockCompilation) {
  75259. this._updateParameters();
  75260. }
  75261. },
  75262. enumerable: true,
  75263. configurable: true
  75264. });
  75265. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75266. /**
  75267. * Gets wether or not the blur is unpacking/repacking floats
  75268. */
  75269. get: function () {
  75270. return this._packedFloat;
  75271. },
  75272. /**
  75273. * Sets wether or not the blur needs to unpack/repack floats
  75274. */
  75275. set: function (v) {
  75276. if (this._packedFloat === v) {
  75277. return;
  75278. }
  75279. this._packedFloat = v;
  75280. if (!this.blockCompilation) {
  75281. this._updateParameters();
  75282. }
  75283. },
  75284. enumerable: true,
  75285. configurable: true
  75286. });
  75287. /**
  75288. * Updates the effect with the current post process compile time values and recompiles the shader.
  75289. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75290. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75291. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75292. * @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
  75293. * @param onCompiled Called when the shader has been compiled.
  75294. * @param onError Called if there is an error when compiling a shader.
  75295. */
  75296. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75297. if (defines === void 0) { defines = null; }
  75298. if (uniforms === void 0) { uniforms = null; }
  75299. if (samplers === void 0) { samplers = null; }
  75300. this._updateParameters(onCompiled, onError);
  75301. };
  75302. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75303. // Generate sampling offsets and weights
  75304. var N = this._kernel;
  75305. var centerIndex = (N - 1) / 2;
  75306. // Generate Gaussian sampling weights over kernel
  75307. var offsets = [];
  75308. var weights = [];
  75309. var totalWeight = 0;
  75310. for (var i = 0; i < N; i++) {
  75311. var u = i / (N - 1);
  75312. var w = this._gaussianWeight(u * 2.0 - 1);
  75313. offsets[i] = (i - centerIndex);
  75314. weights[i] = w;
  75315. totalWeight += w;
  75316. }
  75317. // Normalize weights
  75318. for (var i = 0; i < weights.length; i++) {
  75319. weights[i] /= totalWeight;
  75320. }
  75321. // Optimize: combine samples to take advantage of hardware linear sampling
  75322. // Walk from left to center, combining pairs (symmetrically)
  75323. var linearSamplingWeights = [];
  75324. var linearSamplingOffsets = [];
  75325. var linearSamplingMap = [];
  75326. for (var i = 0; i <= centerIndex; i += 2) {
  75327. var j = Math.min(i + 1, Math.floor(centerIndex));
  75328. var singleCenterSample = i === j;
  75329. if (singleCenterSample) {
  75330. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75331. }
  75332. else {
  75333. var sharedCell = j === centerIndex;
  75334. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75335. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75336. if (offsetLinear === 0) {
  75337. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75338. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75339. }
  75340. else {
  75341. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75342. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75343. }
  75344. }
  75345. }
  75346. for (var i = 0; i < linearSamplingMap.length; i++) {
  75347. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75348. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75349. }
  75350. // Replace with optimized
  75351. offsets = linearSamplingOffsets;
  75352. weights = linearSamplingWeights;
  75353. // Generate shaders
  75354. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75355. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75356. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75357. var defines = "";
  75358. defines += this._staticDefines;
  75359. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75360. if (this._staticDefines.indexOf("DOF") != -1) {
  75361. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75362. varyingCount--;
  75363. }
  75364. for (var i = 0; i < varyingCount; i++) {
  75365. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75366. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75367. }
  75368. var depCount = 0;
  75369. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75370. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75371. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75372. depCount++;
  75373. }
  75374. if (this.packedFloat) {
  75375. defines += "#define PACKEDFLOAT 1";
  75376. }
  75377. this.blockCompilation = false;
  75378. _super.prototype.updateEffect.call(this, defines, null, null, {
  75379. varyingCount: varyingCount,
  75380. depCount: depCount
  75381. }, onCompiled, onError);
  75382. };
  75383. /**
  75384. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75385. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75386. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75387. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75388. * The gaps between physical kernels are compensated for in the weighting of the samples
  75389. * @param idealKernel Ideal blur kernel.
  75390. * @return Nearest best kernel.
  75391. */
  75392. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75393. var v = Math.round(idealKernel);
  75394. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75395. var k = _a[_i];
  75396. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75397. return Math.max(k, 3);
  75398. }
  75399. }
  75400. return Math.max(v, 3);
  75401. };
  75402. /**
  75403. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75404. * @param x The point on the Gaussian distribution to sample.
  75405. * @return the value of the Gaussian function at x.
  75406. */
  75407. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75408. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75409. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75410. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75411. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75412. // truncated at around 1.3% of peak strength.
  75413. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75414. var sigma = (1 / 3);
  75415. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75416. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75417. var weight = (1.0 / denominator) * Math.exp(exponent);
  75418. return weight;
  75419. };
  75420. /**
  75421. * Generates a string that can be used as a floating point number in GLSL.
  75422. * @param x Value to print.
  75423. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75424. * @return GLSL float string.
  75425. */
  75426. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75427. if (decimalFigures === void 0) { decimalFigures = 8; }
  75428. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75429. };
  75430. return BlurPostProcess;
  75431. }(BABYLON.PostProcess));
  75432. BABYLON.BlurPostProcess = BlurPostProcess;
  75433. })(BABYLON || (BABYLON = {}));
  75434. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75435. var BABYLON;
  75436. (function (BABYLON) {
  75437. /**
  75438. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75439. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75440. * based on samples that have a large difference in distance than the center pixel.
  75441. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75442. */
  75443. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75444. __extends(DepthOfFieldBlurPostProcess, _super);
  75445. /**
  75446. * Creates a new instance CircleOfConfusionPostProcess
  75447. * @param name The name of the effect.
  75448. * @param scene The scene the effect belongs to.
  75449. * @param direction The direction the blur should be applied.
  75450. * @param kernel The size of the kernel used to blur.
  75451. * @param options The required width/height ratio to downsize to before computing the render pass.
  75452. * @param camera The camera to apply the render pass to.
  75453. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75454. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75455. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75456. * @param engine The engine which the post process will be applied. (default: current engine)
  75457. * @param reusable If the post process can be reused on the same frame. (default: false)
  75458. * @param textureType Type of textures used when performing the post process. (default: 0)
  75459. * @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)
  75460. */
  75461. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75462. if (imageToBlur === void 0) { imageToBlur = null; }
  75463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75464. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75465. if (blockCompilation === void 0) { blockCompilation = false; }
  75466. 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;
  75467. _this.direction = direction;
  75468. _this.onApplyObservable.add(function (effect) {
  75469. if (imageToBlur != null) {
  75470. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75471. }
  75472. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75473. if (scene.activeCamera) {
  75474. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75475. }
  75476. });
  75477. return _this;
  75478. }
  75479. return DepthOfFieldBlurPostProcess;
  75480. }(BABYLON.BlurPostProcess));
  75481. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75482. })(BABYLON || (BABYLON = {}));
  75483. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75484. var BABYLON;
  75485. (function (BABYLON) {
  75486. /**
  75487. * Options to be set when merging outputs from the default pipeline.
  75488. */
  75489. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75490. function DepthOfFieldMergePostProcessOptions() {
  75491. }
  75492. return DepthOfFieldMergePostProcessOptions;
  75493. }());
  75494. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75495. /**
  75496. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75497. */
  75498. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75499. __extends(DepthOfFieldMergePostProcess, _super);
  75500. /**
  75501. * Creates a new instance of DepthOfFieldMergePostProcess
  75502. * @param name The name of the effect.
  75503. * @param originalFromInput Post process which's input will be used for the merge.
  75504. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75505. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75506. * @param options The required width/height ratio to downsize to before computing the render pass.
  75507. * @param camera The camera to apply the render pass to.
  75508. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75509. * @param engine The engine which the post process will be applied. (default: current engine)
  75510. * @param reusable If the post process can be reused on the same frame. (default: false)
  75511. * @param textureType Type of textures used when performing the post process. (default: 0)
  75512. * @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)
  75513. */
  75514. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75515. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75516. if (blockCompilation === void 0) { blockCompilation = false; }
  75517. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75518. _this.blurSteps = blurSteps;
  75519. _this.onApplyObservable.add(function (effect) {
  75520. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75521. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75522. blurSteps.forEach(function (step, index) {
  75523. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75524. });
  75525. });
  75526. if (!blockCompilation) {
  75527. _this.updateEffect();
  75528. }
  75529. return _this;
  75530. }
  75531. /**
  75532. * Updates the effect with the current post process compile time values and recompiles the shader.
  75533. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75534. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75535. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75536. * @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
  75537. * @param onCompiled Called when the shader has been compiled.
  75538. * @param onError Called if there is an error when compiling a shader.
  75539. */
  75540. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75541. if (defines === void 0) { defines = null; }
  75542. if (uniforms === void 0) { uniforms = null; }
  75543. if (samplers === void 0) { samplers = null; }
  75544. if (!defines) {
  75545. defines = "";
  75546. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75547. }
  75548. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75549. };
  75550. return DepthOfFieldMergePostProcess;
  75551. }(BABYLON.PostProcess));
  75552. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75553. })(BABYLON || (BABYLON = {}));
  75554. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75555. var BABYLON;
  75556. (function (BABYLON) {
  75557. /**
  75558. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75559. */
  75560. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75561. __extends(CircleOfConfusionPostProcess, _super);
  75562. /**
  75563. * Creates a new instance CircleOfConfusionPostProcess
  75564. * @param name The name of the effect.
  75565. * @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.
  75566. * @param options The required width/height ratio to downsize to before computing the render pass.
  75567. * @param camera The camera to apply the render pass to.
  75568. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75569. * @param engine The engine which the post process will be applied. (default: current engine)
  75570. * @param reusable If the post process can be reused on the same frame. (default: false)
  75571. * @param textureType Type of textures used when performing the post process. (default: 0)
  75572. * @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)
  75573. */
  75574. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75575. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75576. if (blockCompilation === void 0) { blockCompilation = false; }
  75577. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75578. /**
  75579. * 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.
  75580. */
  75581. _this.lensSize = 50;
  75582. /**
  75583. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75584. */
  75585. _this.fStop = 1.4;
  75586. /**
  75587. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75588. */
  75589. _this.focusDistance = 2000;
  75590. /**
  75591. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75592. */
  75593. _this.focalLength = 50;
  75594. _this._depthTexture = null;
  75595. _this._depthTexture = depthTexture;
  75596. _this.onApplyObservable.add(function (effect) {
  75597. if (!_this._depthTexture) {
  75598. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75599. return;
  75600. }
  75601. effect.setTexture("depthSampler", _this._depthTexture);
  75602. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75603. var aperture = _this.lensSize / _this.fStop;
  75604. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75605. effect.setFloat('focusDistance', _this.focusDistance);
  75606. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75607. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75608. });
  75609. return _this;
  75610. }
  75611. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75612. /**
  75613. * 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.
  75614. */
  75615. set: function (value) {
  75616. this._depthTexture = value;
  75617. },
  75618. enumerable: true,
  75619. configurable: true
  75620. });
  75621. return CircleOfConfusionPostProcess;
  75622. }(BABYLON.PostProcess));
  75623. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75624. })(BABYLON || (BABYLON = {}));
  75625. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75626. var BABYLON;
  75627. (function (BABYLON) {
  75628. /**
  75629. * Specifies the level of max blur that should be applied when using the depth of field effect
  75630. */
  75631. var DepthOfFieldEffectBlurLevel;
  75632. (function (DepthOfFieldEffectBlurLevel) {
  75633. /**
  75634. * Subtle blur
  75635. */
  75636. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75637. /**
  75638. * Medium blur
  75639. */
  75640. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75641. /**
  75642. * Large blur
  75643. */
  75644. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75645. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75646. ;
  75647. /**
  75648. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75649. */
  75650. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75651. __extends(DepthOfFieldEffect, _super);
  75652. /**
  75653. * Creates a new instance DepthOfFieldEffect
  75654. * @param scene The scene the effect belongs to.
  75655. * @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.
  75656. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75657. * @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)
  75658. */
  75659. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75660. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75661. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75662. if (blockCompilation === void 0) { blockCompilation = false; }
  75663. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75664. return _this._effects;
  75665. }, true) || this;
  75666. /**
  75667. * Internal post processes in depth of field effect
  75668. */
  75669. _this._effects = [];
  75670. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75671. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75672. // 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)
  75673. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75674. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75675. _this._depthOfFieldBlurY = [];
  75676. _this._depthOfFieldBlurX = [];
  75677. var blurCount = 1;
  75678. var kernelSize = 15;
  75679. switch (blurLevel) {
  75680. case DepthOfFieldEffectBlurLevel.High: {
  75681. blurCount = 3;
  75682. kernelSize = 51;
  75683. break;
  75684. }
  75685. case DepthOfFieldEffectBlurLevel.Medium: {
  75686. blurCount = 2;
  75687. kernelSize = 31;
  75688. break;
  75689. }
  75690. default: {
  75691. kernelSize = 15;
  75692. blurCount = 1;
  75693. break;
  75694. }
  75695. }
  75696. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75697. var ratio = 1.0;
  75698. for (var i = 0; i < blurCount; i++) {
  75699. 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);
  75700. blurY.autoClear = false;
  75701. ratio = 0.75 / Math.pow(2, i);
  75702. 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);
  75703. blurX.autoClear = false;
  75704. _this._depthOfFieldBlurY.push(blurY);
  75705. _this._depthOfFieldBlurX.push(blurX);
  75706. }
  75707. // Set all post processes on the effect.
  75708. _this._effects = [_this._circleOfConfusion];
  75709. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75710. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75711. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75712. }
  75713. // Merge blurred images with original image based on circleOfConfusion
  75714. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75715. _this._dofMerge.autoClear = false;
  75716. _this._effects.push(_this._dofMerge);
  75717. return _this;
  75718. }
  75719. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75720. get: function () {
  75721. return this._circleOfConfusion.focalLength;
  75722. },
  75723. /**
  75724. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75725. */
  75726. set: function (value) {
  75727. this._circleOfConfusion.focalLength = value;
  75728. },
  75729. enumerable: true,
  75730. configurable: true
  75731. });
  75732. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75733. get: function () {
  75734. return this._circleOfConfusion.fStop;
  75735. },
  75736. /**
  75737. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75738. */
  75739. set: function (value) {
  75740. this._circleOfConfusion.fStop = value;
  75741. },
  75742. enumerable: true,
  75743. configurable: true
  75744. });
  75745. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75746. get: function () {
  75747. return this._circleOfConfusion.focusDistance;
  75748. },
  75749. /**
  75750. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75751. */
  75752. set: function (value) {
  75753. this._circleOfConfusion.focusDistance = value;
  75754. },
  75755. enumerable: true,
  75756. configurable: true
  75757. });
  75758. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75759. get: function () {
  75760. return this._circleOfConfusion.lensSize;
  75761. },
  75762. /**
  75763. * 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.
  75764. */
  75765. set: function (value) {
  75766. this._circleOfConfusion.lensSize = value;
  75767. },
  75768. enumerable: true,
  75769. configurable: true
  75770. });
  75771. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75772. /**
  75773. * 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.
  75774. */
  75775. set: function (value) {
  75776. this._circleOfConfusion.depthTexture = value;
  75777. },
  75778. enumerable: true,
  75779. configurable: true
  75780. });
  75781. /**
  75782. * Disposes each of the internal effects for a given camera.
  75783. * @param camera The camera to dispose the effect on.
  75784. */
  75785. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75786. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75787. this._effects[effectIndex].dispose(camera);
  75788. }
  75789. };
  75790. /**
  75791. * Internal
  75792. */
  75793. DepthOfFieldEffect.prototype._updateEffects = function () {
  75794. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75795. this._effects[effectIndex].updateEffect();
  75796. }
  75797. };
  75798. /**
  75799. * Internal
  75800. * @returns if all the contained post processes are ready.
  75801. */
  75802. DepthOfFieldEffect.prototype._isReady = function () {
  75803. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75804. if (!this._effects[effectIndex].isReady()) {
  75805. return false;
  75806. }
  75807. }
  75808. return true;
  75809. };
  75810. return DepthOfFieldEffect;
  75811. }(BABYLON.PostProcessRenderEffect));
  75812. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75813. })(BABYLON || (BABYLON = {}));
  75814. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75815. var BABYLON;
  75816. (function (BABYLON) {
  75817. /**
  75818. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75819. */
  75820. var BloomMergePostProcess = /** @class */ (function (_super) {
  75821. __extends(BloomMergePostProcess, _super);
  75822. /**
  75823. * Creates a new instance of @see BloomMergePostProcess
  75824. * @param name The name of the effect.
  75825. * @param originalFromInput Post process which's input will be used for the merge.
  75826. * @param blurred Blurred highlights post process which's output will be used.
  75827. * @param weight Weight of the bloom to be added to the original input.
  75828. * @param options The required width/height ratio to downsize to before computing the render pass.
  75829. * @param camera The camera to apply the render pass to.
  75830. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75831. * @param engine The engine which the post process will be applied. (default: current engine)
  75832. * @param reusable If the post process can be reused on the same frame. (default: false)
  75833. * @param textureType Type of textures used when performing the post process. (default: 0)
  75834. * @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)
  75835. */
  75836. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75837. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75838. if (blockCompilation === void 0) { blockCompilation = false; }
  75839. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75840. _this.weight = weight;
  75841. _this.onApplyObservable.add(function (effect) {
  75842. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75843. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75844. effect.setFloat("bloomWeight", _this.weight);
  75845. });
  75846. if (!blockCompilation) {
  75847. _this.updateEffect();
  75848. }
  75849. return _this;
  75850. }
  75851. return BloomMergePostProcess;
  75852. }(BABYLON.PostProcess));
  75853. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75854. })(BABYLON || (BABYLON = {}));
  75855. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75856. var BABYLON;
  75857. (function (BABYLON) {
  75858. /**
  75859. * 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.
  75860. */
  75861. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75862. __extends(ExtractHighlightsPostProcess, _super);
  75863. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75864. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75865. if (blockCompilation === void 0) { blockCompilation = false; }
  75866. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75867. /**
  75868. * The luminance threshold, pixels below this value will be set to black.
  75869. */
  75870. _this.threshold = 0.9;
  75871. /**
  75872. * Internal
  75873. */
  75874. _this._exposure = 1;
  75875. /**
  75876. * Post process which has the input texture to be used when performing highlight extraction
  75877. */
  75878. _this._inputPostProcess = null;
  75879. _this.onApplyObservable.add(function (effect) {
  75880. if (_this._inputPostProcess) {
  75881. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75882. }
  75883. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75884. effect.setFloat('exposure', _this._exposure);
  75885. });
  75886. return _this;
  75887. }
  75888. return ExtractHighlightsPostProcess;
  75889. }(BABYLON.PostProcess));
  75890. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75891. })(BABYLON || (BABYLON = {}));
  75892. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75893. var BABYLON;
  75894. (function (BABYLON) {
  75895. /**
  75896. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75897. */
  75898. var BloomEffect = /** @class */ (function (_super) {
  75899. __extends(BloomEffect, _super);
  75900. /**
  75901. * Creates a new instance of @see BloomEffect
  75902. * @param scene The scene the effect belongs to.
  75903. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75904. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75905. * @param bloomWeight The the strength of bloom.
  75906. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75907. * @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)
  75908. */
  75909. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75910. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75911. if (blockCompilation === void 0) { blockCompilation = false; }
  75912. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75913. return _this._effects;
  75914. }, true) || this;
  75915. _this.bloomScale = bloomScale;
  75916. /**
  75917. * Internal
  75918. */
  75919. _this._effects = [];
  75920. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75921. _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);
  75922. _this._blurX.alwaysForcePOT = true;
  75923. _this._blurX.autoClear = false;
  75924. _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);
  75925. _this._blurY.alwaysForcePOT = true;
  75926. _this._blurY.autoClear = false;
  75927. _this.kernel = bloomKernel;
  75928. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75929. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75930. _this._merge.autoClear = false;
  75931. _this._effects.push(_this._merge);
  75932. return _this;
  75933. }
  75934. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75935. /**
  75936. * The luminance threshold to find bright areas of the image to bloom.
  75937. */
  75938. get: function () {
  75939. return this._downscale.threshold;
  75940. },
  75941. set: function (value) {
  75942. this._downscale.threshold = value;
  75943. },
  75944. enumerable: true,
  75945. configurable: true
  75946. });
  75947. Object.defineProperty(BloomEffect.prototype, "weight", {
  75948. /**
  75949. * The strength of the bloom.
  75950. */
  75951. get: function () {
  75952. return this._merge.weight;
  75953. },
  75954. set: function (value) {
  75955. this._merge.weight = value;
  75956. },
  75957. enumerable: true,
  75958. configurable: true
  75959. });
  75960. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75961. /**
  75962. * Specifies the size of the bloom blur kernel, relative to the final output size
  75963. */
  75964. get: function () {
  75965. return this._blurX.kernel / this.bloomScale;
  75966. },
  75967. set: function (value) {
  75968. this._blurX.kernel = value * this.bloomScale;
  75969. this._blurY.kernel = value * this.bloomScale;
  75970. },
  75971. enumerable: true,
  75972. configurable: true
  75973. });
  75974. /**
  75975. * Disposes each of the internal effects for a given camera.
  75976. * @param camera The camera to dispose the effect on.
  75977. */
  75978. BloomEffect.prototype.disposeEffects = function (camera) {
  75979. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75980. this._effects[effectIndex].dispose(camera);
  75981. }
  75982. };
  75983. /**
  75984. * Internal
  75985. */
  75986. BloomEffect.prototype._updateEffects = function () {
  75987. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75988. this._effects[effectIndex].updateEffect();
  75989. }
  75990. };
  75991. /**
  75992. * Internal
  75993. * @returns if all the contained post processes are ready.
  75994. */
  75995. BloomEffect.prototype._isReady = function () {
  75996. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75997. if (!this._effects[effectIndex].isReady()) {
  75998. return false;
  75999. }
  76000. }
  76001. return true;
  76002. };
  76003. return BloomEffect;
  76004. }(BABYLON.PostProcessRenderEffect));
  76005. BABYLON.BloomEffect = BloomEffect;
  76006. })(BABYLON || (BABYLON = {}));
  76007. //# sourceMappingURL=babylon.bloomEffect.js.map
  76008. var BABYLON;
  76009. (function (BABYLON) {
  76010. /**
  76011. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76012. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76013. */
  76014. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76015. __extends(DefaultRenderingPipeline, _super);
  76016. /**
  76017. * @constructor
  76018. * @param {string} name - The rendering pipeline name (default: "")
  76019. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76020. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76021. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76022. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76023. */
  76024. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76025. if (name === void 0) { name = ""; }
  76026. if (hdr === void 0) { hdr = true; }
  76027. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76028. if (automaticBuild === void 0) { automaticBuild = true; }
  76029. var _this = _super.call(this, scene.getEngine(), name) || this;
  76030. _this._originalCameras = [];
  76031. /**
  76032. * ID of the sharpen post process,
  76033. */
  76034. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76035. /**
  76036. * ID of the image processing post process;
  76037. */
  76038. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76039. /**
  76040. * ID of the Fast Approximate Anti-Aliasing post process;
  76041. */
  76042. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76043. /**
  76044. * ID of the chromatic aberration post process,
  76045. */
  76046. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76047. /**
  76048. * ID of the grain post process
  76049. */
  76050. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76051. /**
  76052. * Glow post process which adds a glow to emmisive areas of the image
  76053. */
  76054. _this._glowLayer = null;
  76055. /**
  76056. * Animations which can be used to tweak settings over a period of time
  76057. */
  76058. _this.animations = [];
  76059. _this._imageProcessingConfigurationObserver = null;
  76060. // Values
  76061. _this._sharpenEnabled = false;
  76062. _this._bloomEnabled = false;
  76063. _this._depthOfFieldEnabled = false;
  76064. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76065. _this._fxaaEnabled = false;
  76066. _this._imageProcessingEnabled = true;
  76067. _this._bloomScale = 0.5;
  76068. _this._chromaticAberrationEnabled = false;
  76069. _this._grainEnabled = false;
  76070. _this._buildAllowed = true;
  76071. _this._resizeObserver = null;
  76072. _this._hardwareScaleLevel = 1.0;
  76073. _this._bloomKernel = 64;
  76074. /**
  76075. * Specifies the weight of the bloom in the final rendering
  76076. */
  76077. _this._bloomWeight = 0.15;
  76078. /**
  76079. * Specifies the luma threshold for the area that will be blurred by the bloom
  76080. */
  76081. _this._bloomThreshold = 0.9;
  76082. _this._samples = 1;
  76083. _this._hasCleared = false;
  76084. _this._prevPostProcess = null;
  76085. _this._prevPrevPostProcess = null;
  76086. _this._cameras = cameras || scene.cameras;
  76087. _this._originalCameras = _this._cameras.slice();
  76088. _this._buildAllowed = automaticBuild;
  76089. // Initialize
  76090. _this._scene = scene;
  76091. var caps = _this._scene.getEngine().getCaps();
  76092. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76093. // Misc
  76094. if (_this._hdr) {
  76095. if (caps.textureHalfFloatRender) {
  76096. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76097. }
  76098. else if (caps.textureFloatRender) {
  76099. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76100. }
  76101. }
  76102. else {
  76103. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76104. }
  76105. // Attach
  76106. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76107. var engine = _this._scene.getEngine();
  76108. // Create post processes before hand so they can be modified before enabled.
  76109. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76110. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76111. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76112. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76113. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76114. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76115. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76116. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76117. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76118. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76119. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76120. _this.bloomKernel = _this.bloomKernel;
  76121. });
  76122. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76123. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76124. });
  76125. _this._buildPipeline();
  76126. return _this;
  76127. }
  76128. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76129. get: function () {
  76130. return this._sharpenEnabled;
  76131. },
  76132. /**
  76133. * Enable or disable the sharpen process from the pipeline
  76134. */
  76135. set: function (enabled) {
  76136. if (this._sharpenEnabled === enabled) {
  76137. return;
  76138. }
  76139. this._sharpenEnabled = enabled;
  76140. this._buildPipeline();
  76141. },
  76142. enumerable: true,
  76143. configurable: true
  76144. });
  76145. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76146. /**
  76147. * Specifies the size of the bloom blur kernel, relative to the final output size
  76148. */
  76149. get: function () {
  76150. return this._bloomKernel;
  76151. },
  76152. set: function (value) {
  76153. this._bloomKernel = value;
  76154. this.bloom.kernel = value / this._hardwareScaleLevel;
  76155. },
  76156. enumerable: true,
  76157. configurable: true
  76158. });
  76159. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76160. get: function () {
  76161. return this._bloomWeight;
  76162. },
  76163. /**
  76164. * The strength of the bloom.
  76165. */
  76166. set: function (value) {
  76167. if (this._bloomWeight === value) {
  76168. return;
  76169. }
  76170. this.bloom.weight = value;
  76171. this._bloomWeight = value;
  76172. },
  76173. enumerable: true,
  76174. configurable: true
  76175. });
  76176. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76177. get: function () {
  76178. return this._bloomThreshold;
  76179. },
  76180. /**
  76181. * The strength of the bloom.
  76182. */
  76183. set: function (value) {
  76184. if (this._bloomThreshold === value) {
  76185. return;
  76186. }
  76187. this.bloom.threshold = value;
  76188. this._bloomThreshold = value;
  76189. },
  76190. enumerable: true,
  76191. configurable: true
  76192. });
  76193. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76194. get: function () {
  76195. return this._bloomScale;
  76196. },
  76197. /**
  76198. * The scale of the bloom, lower value will provide better performance.
  76199. */
  76200. set: function (value) {
  76201. if (this._bloomScale === value) {
  76202. return;
  76203. }
  76204. this._bloomScale = value;
  76205. // recreate bloom and dispose old as this setting is not dynamic
  76206. this._rebuildBloom();
  76207. this._buildPipeline();
  76208. },
  76209. enumerable: true,
  76210. configurable: true
  76211. });
  76212. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76213. get: function () {
  76214. return this._bloomEnabled;
  76215. },
  76216. /**
  76217. * Enable or disable the bloom from the pipeline
  76218. */
  76219. set: function (enabled) {
  76220. if (this._bloomEnabled === enabled) {
  76221. return;
  76222. }
  76223. this._bloomEnabled = enabled;
  76224. this._buildPipeline();
  76225. },
  76226. enumerable: true,
  76227. configurable: true
  76228. });
  76229. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76230. // recreate bloom and dispose old as this setting is not dynamic
  76231. var oldBloom = this.bloom;
  76232. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76233. this.bloom.threshold = oldBloom.threshold;
  76234. for (var i = 0; i < this._cameras.length; i++) {
  76235. oldBloom.disposeEffects(this._cameras[i]);
  76236. }
  76237. };
  76238. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76239. /**
  76240. * If the depth of field is enabled.
  76241. */
  76242. get: function () {
  76243. return this._depthOfFieldEnabled;
  76244. },
  76245. set: function (enabled) {
  76246. if (this._depthOfFieldEnabled === enabled) {
  76247. return;
  76248. }
  76249. this._depthOfFieldEnabled = enabled;
  76250. this._buildPipeline();
  76251. },
  76252. enumerable: true,
  76253. configurable: true
  76254. });
  76255. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76256. /**
  76257. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76258. */
  76259. get: function () {
  76260. return this._depthOfFieldBlurLevel;
  76261. },
  76262. set: function (value) {
  76263. if (this._depthOfFieldBlurLevel === value) {
  76264. return;
  76265. }
  76266. this._depthOfFieldBlurLevel = value;
  76267. // recreate dof and dispose old as this setting is not dynamic
  76268. var oldDof = this.depthOfField;
  76269. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76270. this.depthOfField.focalLength = oldDof.focalLength;
  76271. this.depthOfField.focusDistance = oldDof.focusDistance;
  76272. this.depthOfField.fStop = oldDof.fStop;
  76273. this.depthOfField.lensSize = oldDof.lensSize;
  76274. for (var i = 0; i < this._cameras.length; i++) {
  76275. oldDof.disposeEffects(this._cameras[i]);
  76276. }
  76277. this._buildPipeline();
  76278. },
  76279. enumerable: true,
  76280. configurable: true
  76281. });
  76282. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76283. get: function () {
  76284. return this._fxaaEnabled;
  76285. },
  76286. /**
  76287. * If the anti aliasing is enabled.
  76288. */
  76289. set: function (enabled) {
  76290. if (this._fxaaEnabled === enabled) {
  76291. return;
  76292. }
  76293. this._fxaaEnabled = enabled;
  76294. this._buildPipeline();
  76295. },
  76296. enumerable: true,
  76297. configurable: true
  76298. });
  76299. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76300. get: function () {
  76301. return this._samples;
  76302. },
  76303. /**
  76304. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76305. */
  76306. set: function (sampleCount) {
  76307. if (this._samples === sampleCount) {
  76308. return;
  76309. }
  76310. this._samples = sampleCount;
  76311. this._buildPipeline();
  76312. },
  76313. enumerable: true,
  76314. configurable: true
  76315. });
  76316. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76317. get: function () {
  76318. return this._imageProcessingEnabled;
  76319. },
  76320. /**
  76321. * If image processing is enabled.
  76322. */
  76323. set: function (enabled) {
  76324. if (this._imageProcessingEnabled === enabled) {
  76325. return;
  76326. }
  76327. this._imageProcessingEnabled = enabled;
  76328. this._buildPipeline();
  76329. },
  76330. enumerable: true,
  76331. configurable: true
  76332. });
  76333. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76334. get: function () {
  76335. return this._glowLayer == null;
  76336. },
  76337. /**
  76338. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76339. */
  76340. set: function (enabled) {
  76341. if (enabled && !this._glowLayer) {
  76342. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76343. }
  76344. else if (!enabled && this._glowLayer) {
  76345. this._glowLayer.dispose();
  76346. this._glowLayer = null;
  76347. }
  76348. },
  76349. enumerable: true,
  76350. configurable: true
  76351. });
  76352. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76353. get: function () {
  76354. return this._chromaticAberrationEnabled;
  76355. },
  76356. /**
  76357. * Enable or disable the chromaticAberration process from the pipeline
  76358. */
  76359. set: function (enabled) {
  76360. if (this._chromaticAberrationEnabled === enabled) {
  76361. return;
  76362. }
  76363. this._chromaticAberrationEnabled = enabled;
  76364. this._buildPipeline();
  76365. },
  76366. enumerable: true,
  76367. configurable: true
  76368. });
  76369. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76370. get: function () {
  76371. return this._grainEnabled;
  76372. },
  76373. /**
  76374. * Enable or disable the grain process from the pipeline
  76375. */
  76376. set: function (enabled) {
  76377. if (this._grainEnabled === enabled) {
  76378. return;
  76379. }
  76380. this._grainEnabled = enabled;
  76381. this._buildPipeline();
  76382. },
  76383. enumerable: true,
  76384. configurable: true
  76385. });
  76386. /**
  76387. * Force the compilation of the entire pipeline.
  76388. */
  76389. DefaultRenderingPipeline.prototype.prepare = function () {
  76390. var previousState = this._buildAllowed;
  76391. this._buildAllowed = true;
  76392. this._buildPipeline();
  76393. this._buildAllowed = previousState;
  76394. };
  76395. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76396. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76397. if (this._hasCleared) {
  76398. postProcess.autoClear = false;
  76399. }
  76400. else {
  76401. postProcess.autoClear = true;
  76402. this._scene.autoClear = false;
  76403. this._hasCleared = true;
  76404. }
  76405. if (!skipTextureSharing) {
  76406. if (this._prevPrevPostProcess) {
  76407. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76408. }
  76409. else {
  76410. postProcess.useOwnOutput();
  76411. }
  76412. if (this._prevPostProcess) {
  76413. this._prevPrevPostProcess = this._prevPostProcess;
  76414. }
  76415. this._prevPostProcess = postProcess;
  76416. }
  76417. };
  76418. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76419. var _this = this;
  76420. if (!this._buildAllowed) {
  76421. return;
  76422. }
  76423. this._scene.autoClear = true;
  76424. var engine = this._scene.getEngine();
  76425. this._disposePostProcesses();
  76426. if (this._cameras !== null) {
  76427. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76428. // get back cameras to be used to reattach pipeline
  76429. this._cameras = this._originalCameras.slice();
  76430. }
  76431. this._reset();
  76432. this._prevPostProcess = null;
  76433. this._prevPrevPostProcess = null;
  76434. this._hasCleared = false;
  76435. if (this.depthOfFieldEnabled) {
  76436. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76437. this.depthOfField.depthTexture = depthTexture;
  76438. if (!this.depthOfField._isReady()) {
  76439. this.depthOfField._updateEffects();
  76440. }
  76441. this.addEffect(this.depthOfField);
  76442. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76443. }
  76444. if (this.bloomEnabled) {
  76445. if (!this.bloom._isReady()) {
  76446. this.bloom._updateEffects();
  76447. }
  76448. this.addEffect(this.bloom);
  76449. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76450. }
  76451. if (this._imageProcessingEnabled) {
  76452. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76453. if (this._hdr) {
  76454. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76455. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76456. }
  76457. else {
  76458. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76459. }
  76460. }
  76461. if (this.sharpenEnabled) {
  76462. if (!this.sharpen.isReady()) {
  76463. this.sharpen.updateEffect();
  76464. }
  76465. this.addEffect(this._sharpenEffect);
  76466. this._setAutoClearAndTextureSharing(this.sharpen);
  76467. }
  76468. if (this.grainEnabled) {
  76469. if (!this.grain.isReady()) {
  76470. this.grain.updateEffect();
  76471. }
  76472. this.addEffect(this._grainEffect);
  76473. this._setAutoClearAndTextureSharing(this.grain);
  76474. }
  76475. if (this.chromaticAberrationEnabled) {
  76476. if (!this.chromaticAberration.isReady()) {
  76477. this.chromaticAberration.updateEffect();
  76478. }
  76479. this.addEffect(this._chromaticAberrationEffect);
  76480. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76481. }
  76482. if (this.fxaaEnabled) {
  76483. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76484. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76485. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76486. }
  76487. if (this._cameras !== null) {
  76488. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76489. }
  76490. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76491. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76492. }
  76493. };
  76494. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76495. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76496. for (var i = 0; i < this._cameras.length; i++) {
  76497. var camera = this._cameras[i];
  76498. if (this.imageProcessing) {
  76499. this.imageProcessing.dispose(camera);
  76500. }
  76501. if (this.fxaa) {
  76502. this.fxaa.dispose(camera);
  76503. }
  76504. // These are created in the constructor and should not be disposed on every pipeline change
  76505. if (disposeNonRecreated) {
  76506. if (this.sharpen) {
  76507. this.sharpen.dispose(camera);
  76508. }
  76509. if (this.depthOfField) {
  76510. this.depthOfField.disposeEffects(camera);
  76511. }
  76512. if (this.bloom) {
  76513. this.bloom.disposeEffects(camera);
  76514. }
  76515. if (this.chromaticAberration) {
  76516. this.chromaticAberration.dispose(camera);
  76517. }
  76518. if (this.grain) {
  76519. this.grain.dispose(camera);
  76520. }
  76521. if (this._glowLayer) {
  76522. this._glowLayer.dispose();
  76523. }
  76524. }
  76525. }
  76526. this.imageProcessing = null;
  76527. this.fxaa = null;
  76528. if (disposeNonRecreated) {
  76529. this.sharpen = null;
  76530. this._sharpenEffect = null;
  76531. this.depthOfField = null;
  76532. this.bloom = null;
  76533. this.chromaticAberration = null;
  76534. this._chromaticAberrationEffect = null;
  76535. this.grain = null;
  76536. this._grainEffect = null;
  76537. this._glowLayer = null;
  76538. }
  76539. };
  76540. /**
  76541. * Dispose of the pipeline and stop all post processes
  76542. */
  76543. DefaultRenderingPipeline.prototype.dispose = function () {
  76544. this._disposePostProcesses(true);
  76545. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76546. this._scene.autoClear = true;
  76547. if (this._resizeObserver) {
  76548. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76549. this._resizeObserver = null;
  76550. }
  76551. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76552. _super.prototype.dispose.call(this);
  76553. };
  76554. /**
  76555. * Serialize the rendering pipeline (Used when exporting)
  76556. * @returns the serialized object
  76557. */
  76558. DefaultRenderingPipeline.prototype.serialize = function () {
  76559. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76560. serializationObject.customType = "DefaultRenderingPipeline";
  76561. return serializationObject;
  76562. };
  76563. /**
  76564. * Parse the serialized pipeline
  76565. * @param source Source pipeline.
  76566. * @param scene The scene to load the pipeline to.
  76567. * @param rootUrl The URL of the serialized pipeline.
  76568. * @returns An instantiated pipeline from the serialized object.
  76569. */
  76570. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76571. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76572. };
  76573. __decorate([
  76574. BABYLON.serialize()
  76575. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76576. __decorate([
  76577. BABYLON.serialize()
  76578. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76579. __decorate([
  76580. BABYLON.serialize()
  76581. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76582. __decorate([
  76583. BABYLON.serialize()
  76584. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76585. __decorate([
  76586. BABYLON.serialize()
  76587. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76588. __decorate([
  76589. BABYLON.serialize()
  76590. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76591. __decorate([
  76592. BABYLON.serialize()
  76593. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76594. __decorate([
  76595. BABYLON.serialize()
  76596. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76597. __decorate([
  76598. BABYLON.serialize()
  76599. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76600. __decorate([
  76601. BABYLON.serialize()
  76602. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76603. __decorate([
  76604. BABYLON.serialize()
  76605. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76606. __decorate([
  76607. BABYLON.serialize()
  76608. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76609. __decorate([
  76610. BABYLON.serialize()
  76611. ], DefaultRenderingPipeline.prototype, "samples", null);
  76612. __decorate([
  76613. BABYLON.serialize()
  76614. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76615. __decorate([
  76616. BABYLON.serialize()
  76617. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76618. __decorate([
  76619. BABYLON.serialize()
  76620. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76621. __decorate([
  76622. BABYLON.serialize()
  76623. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76624. return DefaultRenderingPipeline;
  76625. }(BABYLON.PostProcessRenderPipeline));
  76626. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76627. })(BABYLON || (BABYLON = {}));
  76628. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76629. var BABYLON;
  76630. (function (BABYLON) {
  76631. /**
  76632. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76633. */
  76634. var GeometryBufferRenderer = /** @class */ (function () {
  76635. /**
  76636. * Creates a new G Buffer for the scene
  76637. * @param scene The scene the buffer belongs to
  76638. * @param ratio How big is the buffer related to the main canvas.
  76639. */
  76640. function GeometryBufferRenderer(scene, ratio) {
  76641. if (ratio === void 0) { ratio = 1; }
  76642. this._enablePosition = false;
  76643. this._scene = scene;
  76644. this._ratio = ratio;
  76645. // Render target
  76646. this._createRenderTargets();
  76647. }
  76648. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76649. /**
  76650. * Set the render list (meshes to be rendered) used in the G buffer.
  76651. */
  76652. set: function (meshes) {
  76653. this._multiRenderTarget.renderList = meshes;
  76654. },
  76655. enumerable: true,
  76656. configurable: true
  76657. });
  76658. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76659. /**
  76660. * Gets wether or not G buffer are supported by the running hardware.
  76661. * This requires draw buffer supports
  76662. */
  76663. get: function () {
  76664. return this._multiRenderTarget.isSupported;
  76665. },
  76666. enumerable: true,
  76667. configurable: true
  76668. });
  76669. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76670. /**
  76671. * Gets wether or not position are enabled for the G buffer.
  76672. */
  76673. get: function () {
  76674. return this._enablePosition;
  76675. },
  76676. /**
  76677. * Sets wether or not position are enabled for the G buffer.
  76678. */
  76679. set: function (enable) {
  76680. this._enablePosition = enable;
  76681. this.dispose();
  76682. this._createRenderTargets();
  76683. },
  76684. enumerable: true,
  76685. configurable: true
  76686. });
  76687. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76688. /**
  76689. * Gets the scene associated with the buffer.
  76690. */
  76691. get: function () {
  76692. return this._scene;
  76693. },
  76694. enumerable: true,
  76695. configurable: true
  76696. });
  76697. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76698. /**
  76699. * Gets the ratio used by the buffer during its creation.
  76700. * How big is the buffer related to the main canvas.
  76701. */
  76702. get: function () {
  76703. return this._ratio;
  76704. },
  76705. enumerable: true,
  76706. configurable: true
  76707. });
  76708. /**
  76709. * Checks wether everything is ready to render a submesh to the G buffer.
  76710. * @param subMesh the submesh to check readiness for
  76711. * @param useInstances is the mesh drawn using instance or not
  76712. * @returns true if ready otherwise false
  76713. */
  76714. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76715. var material = subMesh.getMaterial();
  76716. if (material && material.disableDepthWrite) {
  76717. return false;
  76718. }
  76719. var defines = [];
  76720. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76721. var mesh = subMesh.getMesh();
  76722. // Alpha test
  76723. if (material && material.needAlphaTesting()) {
  76724. defines.push("#define ALPHATEST");
  76725. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76726. attribs.push(BABYLON.VertexBuffer.UVKind);
  76727. defines.push("#define UV1");
  76728. }
  76729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76730. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76731. defines.push("#define UV2");
  76732. }
  76733. }
  76734. // Buffers
  76735. if (this._enablePosition) {
  76736. defines.push("#define POSITION");
  76737. }
  76738. // Bones
  76739. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76740. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76741. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76742. if (mesh.numBoneInfluencers > 4) {
  76743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76745. }
  76746. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76747. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76748. }
  76749. else {
  76750. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76751. }
  76752. // Instances
  76753. if (useInstances) {
  76754. defines.push("#define INSTANCES");
  76755. attribs.push("world0");
  76756. attribs.push("world1");
  76757. attribs.push("world2");
  76758. attribs.push("world3");
  76759. }
  76760. // Get correct effect
  76761. var join = defines.join("\n");
  76762. if (this._cachedDefines !== join) {
  76763. this._cachedDefines = join;
  76764. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76765. }
  76766. return this._effect.isReady();
  76767. };
  76768. /**
  76769. * Gets the current underlying G Buffer.
  76770. * @returns the buffer
  76771. */
  76772. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76773. return this._multiRenderTarget;
  76774. };
  76775. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76776. /**
  76777. * Gets the number of samples used to render the buffer (anti aliasing).
  76778. */
  76779. get: function () {
  76780. return this._multiRenderTarget.samples;
  76781. },
  76782. /**
  76783. * Sets the number of samples used to render the buffer (anti aliasing).
  76784. */
  76785. set: function (value) {
  76786. this._multiRenderTarget.samples = value;
  76787. },
  76788. enumerable: true,
  76789. configurable: true
  76790. });
  76791. /**
  76792. * Disposes the renderer and frees up associated resources.
  76793. */
  76794. GeometryBufferRenderer.prototype.dispose = function () {
  76795. this.getGBuffer().dispose();
  76796. };
  76797. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76798. var _this = this;
  76799. var engine = this._scene.getEngine();
  76800. var count = this._enablePosition ? 3 : 2;
  76801. 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 });
  76802. if (!this.isSupported) {
  76803. return;
  76804. }
  76805. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76806. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76807. this._multiRenderTarget.refreshRate = 1;
  76808. this._multiRenderTarget.renderParticles = false;
  76809. this._multiRenderTarget.renderList = null;
  76810. // set default depth value to 1.0 (far away)
  76811. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76812. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76813. });
  76814. // Custom render function
  76815. var renderSubMesh = function (subMesh) {
  76816. var mesh = subMesh.getRenderingMesh();
  76817. var scene = _this._scene;
  76818. var engine = scene.getEngine();
  76819. var material = subMesh.getMaterial();
  76820. if (!material) {
  76821. return;
  76822. }
  76823. // Culling
  76824. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76825. // Managing instances
  76826. var batch = mesh._getInstancesRenderList(subMesh._id);
  76827. if (batch.mustReturn) {
  76828. return;
  76829. }
  76830. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76831. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76832. engine.enableEffect(_this._effect);
  76833. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76834. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76835. _this._effect.setMatrix("view", scene.getViewMatrix());
  76836. // Alpha test
  76837. if (material && material.needAlphaTesting()) {
  76838. var alphaTexture = material.getAlphaTestTexture();
  76839. if (alphaTexture) {
  76840. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76841. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76842. }
  76843. }
  76844. // Bones
  76845. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76846. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76847. }
  76848. // Draw
  76849. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76850. }
  76851. };
  76852. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76853. var index;
  76854. if (depthOnlySubMeshes.length) {
  76855. engine.setColorWrite(false);
  76856. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76857. renderSubMesh(depthOnlySubMeshes.data[index]);
  76858. }
  76859. engine.setColorWrite(true);
  76860. }
  76861. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76862. renderSubMesh(opaqueSubMeshes.data[index]);
  76863. }
  76864. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76865. renderSubMesh(alphaTestSubMeshes.data[index]);
  76866. }
  76867. };
  76868. };
  76869. return GeometryBufferRenderer;
  76870. }());
  76871. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76872. })(BABYLON || (BABYLON = {}));
  76873. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76874. var BABYLON;
  76875. (function (BABYLON) {
  76876. var RefractionPostProcess = /** @class */ (function (_super) {
  76877. __extends(RefractionPostProcess, _super);
  76878. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76879. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76880. _this.color = color;
  76881. _this.depth = depth;
  76882. _this.colorLevel = colorLevel;
  76883. _this._ownRefractionTexture = true;
  76884. _this.onActivateObservable.add(function (cam) {
  76885. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76886. });
  76887. _this.onApplyObservable.add(function (effect) {
  76888. effect.setColor3("baseColor", _this.color);
  76889. effect.setFloat("depth", _this.depth);
  76890. effect.setFloat("colorLevel", _this.colorLevel);
  76891. effect.setTexture("refractionSampler", _this._refTexture);
  76892. });
  76893. return _this;
  76894. }
  76895. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76896. /**
  76897. * Gets or sets the refraction texture
  76898. * Please note that you are responsible for disposing the texture if you set it manually
  76899. */
  76900. get: function () {
  76901. return this._refTexture;
  76902. },
  76903. set: function (value) {
  76904. if (this._refTexture && this._ownRefractionTexture) {
  76905. this._refTexture.dispose();
  76906. }
  76907. this._refTexture = value;
  76908. this._ownRefractionTexture = false;
  76909. },
  76910. enumerable: true,
  76911. configurable: true
  76912. });
  76913. // Methods
  76914. RefractionPostProcess.prototype.dispose = function (camera) {
  76915. if (this._refTexture && this._ownRefractionTexture) {
  76916. this._refTexture.dispose();
  76917. this._refTexture = null;
  76918. }
  76919. _super.prototype.dispose.call(this, camera);
  76920. };
  76921. return RefractionPostProcess;
  76922. }(BABYLON.PostProcess));
  76923. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76924. })(BABYLON || (BABYLON = {}));
  76925. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76926. var BABYLON;
  76927. (function (BABYLON) {
  76928. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76929. __extends(BlackAndWhitePostProcess, _super);
  76930. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76931. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76932. _this.degree = 1;
  76933. _this.onApplyObservable.add(function (effect) {
  76934. effect.setFloat("degree", _this.degree);
  76935. });
  76936. return _this;
  76937. }
  76938. return BlackAndWhitePostProcess;
  76939. }(BABYLON.PostProcess));
  76940. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76941. })(BABYLON || (BABYLON = {}));
  76942. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76943. var BABYLON;
  76944. (function (BABYLON) {
  76945. /**
  76946. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76947. * input texture to perform effects such as edge detection or sharpening
  76948. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76949. */
  76950. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76951. __extends(ConvolutionPostProcess, _super);
  76952. /**
  76953. * Creates a new instance ConvolutionPostProcess
  76954. * @param name The name of the effect.
  76955. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76956. * @param options The required width/height ratio to downsize to before computing the render pass.
  76957. * @param camera The camera to apply the render pass to.
  76958. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76959. * @param engine The engine which the post process will be applied. (default: current engine)
  76960. * @param reusable If the post process can be reused on the same frame. (default: false)
  76961. * @param textureType Type of textures used when performing the post process. (default: 0)
  76962. */
  76963. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76964. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76965. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76966. _this.kernel = kernel;
  76967. _this.onApply = function (effect) {
  76968. effect.setFloat2("screenSize", _this.width, _this.height);
  76969. effect.setArray("kernel", _this.kernel);
  76970. };
  76971. return _this;
  76972. }
  76973. // Statics
  76974. /**
  76975. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76976. */
  76977. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76978. /**
  76979. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76980. */
  76981. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76982. /**
  76983. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76984. */
  76985. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76986. /**
  76987. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76988. */
  76989. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76990. /**
  76991. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76992. */
  76993. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76994. /**
  76995. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76996. */
  76997. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76998. return ConvolutionPostProcess;
  76999. }(BABYLON.PostProcess));
  77000. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77001. })(BABYLON || (BABYLON = {}));
  77002. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77003. var BABYLON;
  77004. (function (BABYLON) {
  77005. var FilterPostProcess = /** @class */ (function (_super) {
  77006. __extends(FilterPostProcess, _super);
  77007. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77008. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77009. _this.kernelMatrix = kernelMatrix;
  77010. _this.onApply = function (effect) {
  77011. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77012. };
  77013. return _this;
  77014. }
  77015. return FilterPostProcess;
  77016. }(BABYLON.PostProcess));
  77017. BABYLON.FilterPostProcess = FilterPostProcess;
  77018. })(BABYLON || (BABYLON = {}));
  77019. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77020. var BABYLON;
  77021. (function (BABYLON) {
  77022. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77023. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77024. __extends(VolumetricLightScatteringPostProcess, _super);
  77025. /**
  77026. * @constructor
  77027. * @param {string} name - The post-process name
  77028. * @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)
  77029. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77030. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77031. * @param {number} samples - The post-process quality, default 100
  77032. * @param {number} samplingMode - The post-process filtering mode
  77033. * @param {BABYLON.Engine} engine - The babylon engine
  77034. * @param {boolean} reusable - If the post-process is reusable
  77035. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77036. */
  77037. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77038. if (samples === void 0) { samples = 100; }
  77039. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77040. 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;
  77041. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77042. /**
  77043. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77044. */
  77045. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77046. /**
  77047. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77048. */
  77049. _this.useCustomMeshPosition = false;
  77050. /**
  77051. * If the post-process should inverse the light scattering direction
  77052. */
  77053. _this.invert = true;
  77054. /**
  77055. * Array containing the excluded meshes not rendered in the internal pass
  77056. */
  77057. _this.excludedMeshes = new Array();
  77058. /**
  77059. * Controls the overall intensity of the post-process
  77060. */
  77061. _this.exposure = 0.3;
  77062. /**
  77063. * Dissipates each sample's contribution in range [0, 1]
  77064. */
  77065. _this.decay = 0.96815;
  77066. /**
  77067. * Controls the overall intensity of each sample
  77068. */
  77069. _this.weight = 0.58767;
  77070. /**
  77071. * Controls the density of each sample
  77072. */
  77073. _this.density = 0.926;
  77074. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77075. engine = scene.getEngine();
  77076. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77077. // Configure mesh
  77078. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77079. // Configure
  77080. _this._createPass(scene, ratio.passRatio || ratio);
  77081. _this.onActivate = function (camera) {
  77082. if (!_this.isSupported) {
  77083. _this.dispose(camera);
  77084. }
  77085. _this.onActivate = null;
  77086. };
  77087. _this.onApplyObservable.add(function (effect) {
  77088. _this._updateMeshScreenCoordinates(scene);
  77089. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77090. effect.setFloat("exposure", _this.exposure);
  77091. effect.setFloat("decay", _this.decay);
  77092. effect.setFloat("weight", _this.weight);
  77093. effect.setFloat("density", _this.density);
  77094. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77095. });
  77096. return _this;
  77097. }
  77098. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77099. get: function () {
  77100. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77101. return false;
  77102. },
  77103. set: function (useDiffuseColor) {
  77104. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77105. },
  77106. enumerable: true,
  77107. configurable: true
  77108. });
  77109. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77110. return "VolumetricLightScatteringPostProcess";
  77111. };
  77112. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77113. var mesh = subMesh.getMesh();
  77114. // Render this.mesh as default
  77115. if (mesh === this.mesh && mesh.material) {
  77116. return mesh.material.isReady(mesh);
  77117. }
  77118. var defines = [];
  77119. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77120. var material = subMesh.getMaterial();
  77121. // Alpha test
  77122. if (material) {
  77123. if (material.needAlphaTesting()) {
  77124. defines.push("#define ALPHATEST");
  77125. }
  77126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77127. attribs.push(BABYLON.VertexBuffer.UVKind);
  77128. defines.push("#define UV1");
  77129. }
  77130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77131. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77132. defines.push("#define UV2");
  77133. }
  77134. }
  77135. // Bones
  77136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77137. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77138. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77139. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77140. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77141. }
  77142. else {
  77143. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77144. }
  77145. // Instances
  77146. if (useInstances) {
  77147. defines.push("#define INSTANCES");
  77148. attribs.push("world0");
  77149. attribs.push("world1");
  77150. attribs.push("world2");
  77151. attribs.push("world3");
  77152. }
  77153. // Get correct effect
  77154. var join = defines.join("\n");
  77155. if (this._cachedDefines !== join) {
  77156. this._cachedDefines = join;
  77157. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77158. }
  77159. return this._volumetricLightScatteringPass.isReady();
  77160. };
  77161. /**
  77162. * Sets the new light position for light scattering effect
  77163. * @param {BABYLON.Vector3} The new custom light position
  77164. */
  77165. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77166. this.customMeshPosition = position;
  77167. };
  77168. /**
  77169. * Returns the light position for light scattering effect
  77170. * @return {BABYLON.Vector3} The custom light position
  77171. */
  77172. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77173. return this.customMeshPosition;
  77174. };
  77175. /**
  77176. * Disposes the internal assets and detaches the post-process from the camera
  77177. */
  77178. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77179. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77180. if (rttIndex !== -1) {
  77181. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77182. }
  77183. this._volumetricLightScatteringRTT.dispose();
  77184. _super.prototype.dispose.call(this, camera);
  77185. };
  77186. /**
  77187. * Returns the render target texture used by the post-process
  77188. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77189. */
  77190. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77191. return this._volumetricLightScatteringRTT;
  77192. };
  77193. // Private methods
  77194. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77195. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77196. return true;
  77197. }
  77198. return false;
  77199. };
  77200. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77201. var _this = this;
  77202. var engine = scene.getEngine();
  77203. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77204. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77205. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77206. this._volumetricLightScatteringRTT.renderList = null;
  77207. this._volumetricLightScatteringRTT.renderParticles = false;
  77208. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77209. var camera = this.getCamera();
  77210. if (camera) {
  77211. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77212. }
  77213. else {
  77214. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77215. }
  77216. // Custom render function for submeshes
  77217. var renderSubMesh = function (subMesh) {
  77218. var mesh = subMesh.getRenderingMesh();
  77219. if (_this._meshExcluded(mesh)) {
  77220. return;
  77221. }
  77222. var material = subMesh.getMaterial();
  77223. if (!material) {
  77224. return;
  77225. }
  77226. var scene = mesh.getScene();
  77227. var engine = scene.getEngine();
  77228. // Culling
  77229. engine.setState(material.backFaceCulling);
  77230. // Managing instances
  77231. var batch = mesh._getInstancesRenderList(subMesh._id);
  77232. if (batch.mustReturn) {
  77233. return;
  77234. }
  77235. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77236. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77237. var effect = _this._volumetricLightScatteringPass;
  77238. if (mesh === _this.mesh) {
  77239. if (subMesh.effect) {
  77240. effect = subMesh.effect;
  77241. }
  77242. else {
  77243. effect = material.getEffect();
  77244. }
  77245. }
  77246. engine.enableEffect(effect);
  77247. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77248. if (mesh === _this.mesh) {
  77249. material.bind(mesh.getWorldMatrix(), mesh);
  77250. }
  77251. else {
  77252. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77253. // Alpha test
  77254. if (material && material.needAlphaTesting()) {
  77255. var alphaTexture = material.getAlphaTestTexture();
  77256. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77257. if (alphaTexture) {
  77258. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77259. }
  77260. }
  77261. // Bones
  77262. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77263. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77264. }
  77265. }
  77266. // Draw
  77267. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77268. }
  77269. };
  77270. // Render target texture callbacks
  77271. var savedSceneClearColor;
  77272. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77273. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77274. savedSceneClearColor = scene.clearColor;
  77275. scene.clearColor = sceneClearColor;
  77276. });
  77277. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77278. scene.clearColor = savedSceneClearColor;
  77279. });
  77280. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77281. var engine = scene.getEngine();
  77282. var index;
  77283. if (depthOnlySubMeshes.length) {
  77284. engine.setColorWrite(false);
  77285. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77286. renderSubMesh(depthOnlySubMeshes.data[index]);
  77287. }
  77288. engine.setColorWrite(true);
  77289. }
  77290. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77291. renderSubMesh(opaqueSubMeshes.data[index]);
  77292. }
  77293. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77294. renderSubMesh(alphaTestSubMeshes.data[index]);
  77295. }
  77296. if (transparentSubMeshes.length) {
  77297. // Sort sub meshes
  77298. for (index = 0; index < transparentSubMeshes.length; index++) {
  77299. var submesh = transparentSubMeshes.data[index];
  77300. var boundingInfo = submesh.getBoundingInfo();
  77301. if (boundingInfo && scene.activeCamera) {
  77302. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77303. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77304. }
  77305. }
  77306. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77307. sortedArray.sort(function (a, b) {
  77308. // Alpha index first
  77309. if (a._alphaIndex > b._alphaIndex) {
  77310. return 1;
  77311. }
  77312. if (a._alphaIndex < b._alphaIndex) {
  77313. return -1;
  77314. }
  77315. // Then distance to camera
  77316. if (a._distanceToCamera < b._distanceToCamera) {
  77317. return 1;
  77318. }
  77319. if (a._distanceToCamera > b._distanceToCamera) {
  77320. return -1;
  77321. }
  77322. return 0;
  77323. });
  77324. // Render sub meshes
  77325. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77326. for (index = 0; index < sortedArray.length; index++) {
  77327. renderSubMesh(sortedArray[index]);
  77328. }
  77329. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77330. }
  77331. };
  77332. };
  77333. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77334. var transform = scene.getTransformMatrix();
  77335. var meshPosition;
  77336. if (this.useCustomMeshPosition) {
  77337. meshPosition = this.customMeshPosition;
  77338. }
  77339. else if (this.attachedNode) {
  77340. meshPosition = this.attachedNode.position;
  77341. }
  77342. else {
  77343. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77344. }
  77345. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77346. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77347. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77348. if (this.invert)
  77349. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77350. };
  77351. // Static methods
  77352. /**
  77353. * Creates a default mesh for the Volumeric Light Scattering post-process
  77354. * @param {string} The mesh name
  77355. * @param {BABYLON.Scene} The scene where to create the mesh
  77356. * @return {BABYLON.Mesh} the default mesh
  77357. */
  77358. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77359. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77360. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77361. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77362. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77363. mesh.material = material;
  77364. return mesh;
  77365. };
  77366. __decorate([
  77367. BABYLON.serializeAsVector3()
  77368. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77369. __decorate([
  77370. BABYLON.serialize()
  77371. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77372. __decorate([
  77373. BABYLON.serialize()
  77374. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77375. __decorate([
  77376. BABYLON.serializeAsMeshReference()
  77377. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77378. __decorate([
  77379. BABYLON.serialize()
  77380. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77381. __decorate([
  77382. BABYLON.serialize()
  77383. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77384. __decorate([
  77385. BABYLON.serialize()
  77386. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77387. __decorate([
  77388. BABYLON.serialize()
  77389. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77390. __decorate([
  77391. BABYLON.serialize()
  77392. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77393. return VolumetricLightScatteringPostProcess;
  77394. }(BABYLON.PostProcess));
  77395. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77396. })(BABYLON || (BABYLON = {}));
  77397. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77398. //
  77399. // This post-process allows the modification of rendered colors by using
  77400. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77401. //
  77402. // The object needs to be provided an url to a texture containing the color
  77403. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77404. // Use an image editing software to tweak the LUT to match your needs.
  77405. //
  77406. // For an example of a color LUT, see here:
  77407. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77408. // For explanations on color grading, see here:
  77409. // http://udn.epicgames.com/Three/ColorGrading.html
  77410. //
  77411. var BABYLON;
  77412. (function (BABYLON) {
  77413. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77414. __extends(ColorCorrectionPostProcess, _super);
  77415. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77416. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77417. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77418. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77419. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77420. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77421. _this.onApply = function (effect) {
  77422. effect.setTexture("colorTable", _this._colorTableTexture);
  77423. };
  77424. return _this;
  77425. }
  77426. return ColorCorrectionPostProcess;
  77427. }(BABYLON.PostProcess));
  77428. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77429. })(BABYLON || (BABYLON = {}));
  77430. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77431. var BABYLON;
  77432. (function (BABYLON) {
  77433. /** Defines operator used for tonemapping */
  77434. var TonemappingOperator;
  77435. (function (TonemappingOperator) {
  77436. /** Hable */
  77437. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77438. /** Reinhard */
  77439. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77440. /** HejiDawson */
  77441. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77442. /** Photographic */
  77443. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77444. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77445. ;
  77446. /**
  77447. * Defines a post process to apply tone mapping
  77448. */
  77449. var TonemapPostProcess = /** @class */ (function (_super) {
  77450. __extends(TonemapPostProcess, _super);
  77451. /**
  77452. * Creates a new TonemapPostProcess
  77453. * @param name defines the name of the postprocess
  77454. * @param _operator defines the operator to use
  77455. * @param exposureAdjustment defines the required exposure adjustement
  77456. * @param camera defines the camera to use (can be null)
  77457. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77458. * @param engine defines the hosting engine (can be ignore if camera is set)
  77459. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77460. */
  77461. function TonemapPostProcess(name, _operator,
  77462. /** Defines the required exposure adjustement */
  77463. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77464. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77465. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77466. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77467. _this._operator = _operator;
  77468. _this.exposureAdjustment = exposureAdjustment;
  77469. var defines = "#define ";
  77470. if (_this._operator === TonemappingOperator.Hable)
  77471. defines += "HABLE_TONEMAPPING";
  77472. else if (_this._operator === TonemappingOperator.Reinhard)
  77473. defines += "REINHARD_TONEMAPPING";
  77474. else if (_this._operator === TonemappingOperator.HejiDawson)
  77475. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77476. else if (_this._operator === TonemappingOperator.Photographic)
  77477. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77478. //sadly a second call to create the effect.
  77479. _this.updateEffect(defines);
  77480. _this.onApply = function (effect) {
  77481. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77482. };
  77483. return _this;
  77484. }
  77485. return TonemapPostProcess;
  77486. }(BABYLON.PostProcess));
  77487. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77488. })(BABYLON || (BABYLON = {}));
  77489. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77490. var BABYLON;
  77491. (function (BABYLON) {
  77492. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77493. __extends(DisplayPassPostProcess, _super);
  77494. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77495. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77496. }
  77497. return DisplayPassPostProcess;
  77498. }(BABYLON.PostProcess));
  77499. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77500. })(BABYLON || (BABYLON = {}));
  77501. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77502. var BABYLON;
  77503. (function (BABYLON) {
  77504. var HighlightsPostProcess = /** @class */ (function (_super) {
  77505. __extends(HighlightsPostProcess, _super);
  77506. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77507. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77508. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77509. }
  77510. return HighlightsPostProcess;
  77511. }(BABYLON.PostProcess));
  77512. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77513. })(BABYLON || (BABYLON = {}));
  77514. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77515. var BABYLON;
  77516. (function (BABYLON) {
  77517. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77518. __extends(ImageProcessingPostProcess, _super);
  77519. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77520. if (camera === void 0) { camera = null; }
  77521. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77522. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77523. _this._fromLinearSpace = true;
  77524. /**
  77525. * Defines cache preventing GC.
  77526. */
  77527. _this._defines = {
  77528. IMAGEPROCESSING: false,
  77529. VIGNETTE: false,
  77530. VIGNETTEBLENDMODEMULTIPLY: false,
  77531. VIGNETTEBLENDMODEOPAQUE: false,
  77532. TONEMAPPING: false,
  77533. CONTRAST: false,
  77534. COLORCURVES: false,
  77535. COLORGRADING: false,
  77536. COLORGRADING3D: false,
  77537. FROMLINEARSPACE: false,
  77538. SAMPLER3DGREENDEPTH: false,
  77539. SAMPLER3DBGRMAP: false,
  77540. IMAGEPROCESSINGPOSTPROCESS: false,
  77541. EXPOSURE: false,
  77542. };
  77543. // Setup the configuration as forced by the constructor. This would then not force the
  77544. // scene materials output in linear space and let untouched the default forward pass.
  77545. if (imageProcessingConfiguration) {
  77546. imageProcessingConfiguration.applyByPostProcess = true;
  77547. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77548. // This will cause the shader to be compiled
  77549. _this.fromLinearSpace = false;
  77550. }
  77551. // Setup the default processing configuration to the scene.
  77552. else {
  77553. _this._attachImageProcessingConfiguration(null, true);
  77554. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77555. }
  77556. _this.onApply = function (effect) {
  77557. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77558. };
  77559. return _this;
  77560. }
  77561. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77562. /**
  77563. * Gets the image processing configuration used either in this material.
  77564. */
  77565. get: function () {
  77566. return this._imageProcessingConfiguration;
  77567. },
  77568. /**
  77569. * Sets the Default image processing configuration used either in the this material.
  77570. *
  77571. * If sets to null, the scene one is in use.
  77572. */
  77573. set: function (value) {
  77574. this._attachImageProcessingConfiguration(value);
  77575. },
  77576. enumerable: true,
  77577. configurable: true
  77578. });
  77579. /**
  77580. * Attaches a new image processing configuration to the PBR Material.
  77581. * @param configuration
  77582. */
  77583. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77584. var _this = this;
  77585. if (doNotBuild === void 0) { doNotBuild = false; }
  77586. if (configuration === this._imageProcessingConfiguration) {
  77587. return;
  77588. }
  77589. // Detaches observer.
  77590. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77591. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77592. }
  77593. // Pick the scene configuration if needed.
  77594. if (!configuration) {
  77595. var scene = null;
  77596. var engine = this.getEngine();
  77597. var camera = this.getCamera();
  77598. if (camera) {
  77599. scene = camera.getScene();
  77600. }
  77601. else if (engine && engine.scenes) {
  77602. var scenes = engine.scenes;
  77603. scene = scenes[scenes.length - 1];
  77604. }
  77605. else {
  77606. scene = BABYLON.Engine.LastCreatedScene;
  77607. }
  77608. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77609. }
  77610. else {
  77611. this._imageProcessingConfiguration = configuration;
  77612. }
  77613. // Attaches observer.
  77614. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77615. _this._updateParameters();
  77616. });
  77617. // Ensure the effect will be rebuilt.
  77618. if (!doNotBuild) {
  77619. this._updateParameters();
  77620. }
  77621. };
  77622. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77623. /**
  77624. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77625. */
  77626. get: function () {
  77627. return this.imageProcessingConfiguration.colorCurves;
  77628. },
  77629. /**
  77630. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77631. */
  77632. set: function (value) {
  77633. this.imageProcessingConfiguration.colorCurves = value;
  77634. },
  77635. enumerable: true,
  77636. configurable: true
  77637. });
  77638. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77639. /**
  77640. * Gets wether the color curves effect is enabled.
  77641. */
  77642. get: function () {
  77643. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77644. },
  77645. /**
  77646. * Sets wether the color curves effect is enabled.
  77647. */
  77648. set: function (value) {
  77649. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77650. },
  77651. enumerable: true,
  77652. configurable: true
  77653. });
  77654. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77655. /**
  77656. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77657. */
  77658. get: function () {
  77659. return this.imageProcessingConfiguration.colorGradingTexture;
  77660. },
  77661. /**
  77662. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77663. */
  77664. set: function (value) {
  77665. this.imageProcessingConfiguration.colorGradingTexture = value;
  77666. },
  77667. enumerable: true,
  77668. configurable: true
  77669. });
  77670. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77671. /**
  77672. * Gets wether the color grading effect is enabled.
  77673. */
  77674. get: function () {
  77675. return this.imageProcessingConfiguration.colorGradingEnabled;
  77676. },
  77677. /**
  77678. * Gets wether the color grading effect is enabled.
  77679. */
  77680. set: function (value) {
  77681. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77682. },
  77683. enumerable: true,
  77684. configurable: true
  77685. });
  77686. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77687. /**
  77688. * Gets exposure used in the effect.
  77689. */
  77690. get: function () {
  77691. return this.imageProcessingConfiguration.exposure;
  77692. },
  77693. /**
  77694. * Sets exposure used in the effect.
  77695. */
  77696. set: function (value) {
  77697. this.imageProcessingConfiguration.exposure = value;
  77698. },
  77699. enumerable: true,
  77700. configurable: true
  77701. });
  77702. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77703. /**
  77704. * Gets wether tonemapping is enabled or not.
  77705. */
  77706. get: function () {
  77707. return this._imageProcessingConfiguration.toneMappingEnabled;
  77708. },
  77709. /**
  77710. * Sets wether tonemapping is enabled or not
  77711. */
  77712. set: function (value) {
  77713. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77714. },
  77715. enumerable: true,
  77716. configurable: true
  77717. });
  77718. ;
  77719. ;
  77720. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77721. /**
  77722. * Gets contrast used in the effect.
  77723. */
  77724. get: function () {
  77725. return this.imageProcessingConfiguration.contrast;
  77726. },
  77727. /**
  77728. * Sets contrast used in the effect.
  77729. */
  77730. set: function (value) {
  77731. this.imageProcessingConfiguration.contrast = value;
  77732. },
  77733. enumerable: true,
  77734. configurable: true
  77735. });
  77736. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77737. /**
  77738. * Gets Vignette stretch size.
  77739. */
  77740. get: function () {
  77741. return this.imageProcessingConfiguration.vignetteStretch;
  77742. },
  77743. /**
  77744. * Sets Vignette stretch size.
  77745. */
  77746. set: function (value) {
  77747. this.imageProcessingConfiguration.vignetteStretch = value;
  77748. },
  77749. enumerable: true,
  77750. configurable: true
  77751. });
  77752. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77753. /**
  77754. * Gets Vignette centre X Offset.
  77755. */
  77756. get: function () {
  77757. return this.imageProcessingConfiguration.vignetteCentreX;
  77758. },
  77759. /**
  77760. * Sets Vignette centre X Offset.
  77761. */
  77762. set: function (value) {
  77763. this.imageProcessingConfiguration.vignetteCentreX = value;
  77764. },
  77765. enumerable: true,
  77766. configurable: true
  77767. });
  77768. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77769. /**
  77770. * Gets Vignette centre Y Offset.
  77771. */
  77772. get: function () {
  77773. return this.imageProcessingConfiguration.vignetteCentreY;
  77774. },
  77775. /**
  77776. * Sets Vignette centre Y Offset.
  77777. */
  77778. set: function (value) {
  77779. this.imageProcessingConfiguration.vignetteCentreY = value;
  77780. },
  77781. enumerable: true,
  77782. configurable: true
  77783. });
  77784. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77785. /**
  77786. * Gets Vignette weight or intensity of the vignette effect.
  77787. */
  77788. get: function () {
  77789. return this.imageProcessingConfiguration.vignetteWeight;
  77790. },
  77791. /**
  77792. * Sets Vignette weight or intensity of the vignette effect.
  77793. */
  77794. set: function (value) {
  77795. this.imageProcessingConfiguration.vignetteWeight = value;
  77796. },
  77797. enumerable: true,
  77798. configurable: true
  77799. });
  77800. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77801. /**
  77802. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77803. * if vignetteEnabled is set to true.
  77804. */
  77805. get: function () {
  77806. return this.imageProcessingConfiguration.vignetteColor;
  77807. },
  77808. /**
  77809. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77810. * if vignetteEnabled is set to true.
  77811. */
  77812. set: function (value) {
  77813. this.imageProcessingConfiguration.vignetteColor = value;
  77814. },
  77815. enumerable: true,
  77816. configurable: true
  77817. });
  77818. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77819. /**
  77820. * Gets Camera field of view used by the Vignette effect.
  77821. */
  77822. get: function () {
  77823. return this.imageProcessingConfiguration.vignetteCameraFov;
  77824. },
  77825. /**
  77826. * Sets Camera field of view used by the Vignette effect.
  77827. */
  77828. set: function (value) {
  77829. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77830. },
  77831. enumerable: true,
  77832. configurable: true
  77833. });
  77834. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77835. /**
  77836. * Gets the vignette blend mode allowing different kind of effect.
  77837. */
  77838. get: function () {
  77839. return this.imageProcessingConfiguration.vignetteBlendMode;
  77840. },
  77841. /**
  77842. * Sets the vignette blend mode allowing different kind of effect.
  77843. */
  77844. set: function (value) {
  77845. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77846. },
  77847. enumerable: true,
  77848. configurable: true
  77849. });
  77850. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77851. /**
  77852. * Gets wether the vignette effect is enabled.
  77853. */
  77854. get: function () {
  77855. return this.imageProcessingConfiguration.vignetteEnabled;
  77856. },
  77857. /**
  77858. * Sets wether the vignette effect is enabled.
  77859. */
  77860. set: function (value) {
  77861. this.imageProcessingConfiguration.vignetteEnabled = value;
  77862. },
  77863. enumerable: true,
  77864. configurable: true
  77865. });
  77866. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77867. /**
  77868. * Gets wether the input of the processing is in Gamma or Linear Space.
  77869. */
  77870. get: function () {
  77871. return this._fromLinearSpace;
  77872. },
  77873. /**
  77874. * Sets wether the input of the processing is in Gamma or Linear Space.
  77875. */
  77876. set: function (value) {
  77877. if (this._fromLinearSpace === value) {
  77878. return;
  77879. }
  77880. this._fromLinearSpace = value;
  77881. this._updateParameters();
  77882. },
  77883. enumerable: true,
  77884. configurable: true
  77885. });
  77886. ImageProcessingPostProcess.prototype.getClassName = function () {
  77887. return "ImageProcessingPostProcess";
  77888. };
  77889. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77890. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77891. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77892. var defines = "";
  77893. for (var define in this._defines) {
  77894. if (this._defines[define]) {
  77895. defines += "#define " + define + ";\r\n";
  77896. }
  77897. }
  77898. var samplers = ["textureSampler"];
  77899. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77900. var uniforms = ["scale"];
  77901. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77902. this.updateEffect(defines, uniforms, samplers);
  77903. };
  77904. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77905. _super.prototype.dispose.call(this, camera);
  77906. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77907. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77908. }
  77909. this.imageProcessingConfiguration.applyByPostProcess = false;
  77910. };
  77911. __decorate([
  77912. BABYLON.serialize()
  77913. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77914. return ImageProcessingPostProcess;
  77915. }(BABYLON.PostProcess));
  77916. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77917. })(BABYLON || (BABYLON = {}));
  77918. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77919. var BABYLON;
  77920. (function (BABYLON) {
  77921. /**
  77922. * Class used to store bone information
  77923. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77924. */
  77925. var Bone = /** @class */ (function (_super) {
  77926. __extends(Bone, _super);
  77927. /**
  77928. * Create a new bone
  77929. * @param name defines the bone name
  77930. * @param skeleton defines the parent skeleton
  77931. * @param parentBone defines the parent (can be null if the bone is the root)
  77932. * @param localMatrix defines the local matrix
  77933. * @param restPose defines the rest pose matrix
  77934. * @param baseMatrix defines the base matrix
  77935. * @param index defines index of the bone in the hiearchy
  77936. */
  77937. function Bone(
  77938. /**
  77939. * defines the bone name
  77940. */
  77941. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77942. if (parentBone === void 0) { parentBone = null; }
  77943. if (localMatrix === void 0) { localMatrix = null; }
  77944. if (restPose === void 0) { restPose = null; }
  77945. if (baseMatrix === void 0) { baseMatrix = null; }
  77946. if (index === void 0) { index = null; }
  77947. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77948. _this.name = name;
  77949. /**
  77950. * Gets the list of child bones
  77951. */
  77952. _this.children = new Array();
  77953. /** Gets the animations associated with this bone */
  77954. _this.animations = new Array();
  77955. /**
  77956. * @hidden Internal only
  77957. * Set this value to map this bone to a different index in the transform matrices
  77958. * Set this value to -1 to exclude the bone from the transform matrices
  77959. */
  77960. _this._index = null;
  77961. _this._absoluteTransform = new BABYLON.Matrix();
  77962. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77963. _this._scalingDeterminant = 1;
  77964. _this._worldTransform = new BABYLON.Matrix();
  77965. _this._needToDecompose = true;
  77966. _this._needToCompose = false;
  77967. _this._skeleton = skeleton;
  77968. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77969. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77970. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77971. _this._index = index;
  77972. skeleton.bones.push(_this);
  77973. _this.setParent(parentBone, false);
  77974. if (baseMatrix || localMatrix) {
  77975. _this._updateDifferenceMatrix();
  77976. }
  77977. return _this;
  77978. }
  77979. Object.defineProperty(Bone.prototype, "_matrix", {
  77980. /** @hidden */
  77981. get: function () {
  77982. this._compose();
  77983. return this._localMatrix;
  77984. },
  77985. /** @hidden */
  77986. set: function (value) {
  77987. this._localMatrix.copyFrom(value);
  77988. this._needToDecompose = true;
  77989. },
  77990. enumerable: true,
  77991. configurable: true
  77992. });
  77993. // Members
  77994. /**
  77995. * Gets the parent skeleton
  77996. * @returns a skeleton
  77997. */
  77998. Bone.prototype.getSkeleton = function () {
  77999. return this._skeleton;
  78000. };
  78001. /**
  78002. * Gets parent bone
  78003. * @returns a bone or null if the bone is the root of the bone hierarchy
  78004. */
  78005. Bone.prototype.getParent = function () {
  78006. return this._parent;
  78007. };
  78008. /**
  78009. * Sets the parent bone
  78010. * @param parent defines the parent (can be null if the bone is the root)
  78011. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78012. */
  78013. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78014. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78015. if (this._parent === parent) {
  78016. return;
  78017. }
  78018. if (this._parent) {
  78019. var index = this._parent.children.indexOf(this);
  78020. if (index !== -1) {
  78021. this._parent.children.splice(index, 1);
  78022. }
  78023. }
  78024. this._parent = parent;
  78025. if (this._parent) {
  78026. this._parent.children.push(this);
  78027. }
  78028. if (updateDifferenceMatrix) {
  78029. this._updateDifferenceMatrix();
  78030. }
  78031. this.markAsDirty();
  78032. };
  78033. /**
  78034. * Gets the local matrix
  78035. * @returns a matrix
  78036. */
  78037. Bone.prototype.getLocalMatrix = function () {
  78038. this._compose();
  78039. return this._localMatrix;
  78040. };
  78041. /**
  78042. * Gets the base matrix (initial matrix which remains unchanged)
  78043. * @returns a matrix
  78044. */
  78045. Bone.prototype.getBaseMatrix = function () {
  78046. return this._baseMatrix;
  78047. };
  78048. /**
  78049. * Gets the rest pose matrix
  78050. * @returns a matrix
  78051. */
  78052. Bone.prototype.getRestPose = function () {
  78053. return this._restPose;
  78054. };
  78055. /**
  78056. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78057. */
  78058. Bone.prototype.getWorldMatrix = function () {
  78059. return this._worldTransform;
  78060. };
  78061. /**
  78062. * Sets the local matrix to rest pose matrix
  78063. */
  78064. Bone.prototype.returnToRest = function () {
  78065. this.updateMatrix(this._restPose.clone());
  78066. };
  78067. /**
  78068. * Gets the inverse of the absolute transform matrix.
  78069. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78070. * @returns a matrix
  78071. */
  78072. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78073. return this._invertedAbsoluteTransform;
  78074. };
  78075. /**
  78076. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78077. * @returns a matrix
  78078. */
  78079. Bone.prototype.getAbsoluteTransform = function () {
  78080. return this._absoluteTransform;
  78081. };
  78082. Object.defineProperty(Bone.prototype, "position", {
  78083. // Properties (matches AbstractMesh properties)
  78084. /** Gets or sets current position (in local space) */
  78085. get: function () {
  78086. this._decompose();
  78087. return this._localPosition;
  78088. },
  78089. set: function (newPosition) {
  78090. this._decompose();
  78091. this._localPosition.copyFrom(newPosition);
  78092. this._markAsDirtyAndCompose();
  78093. },
  78094. enumerable: true,
  78095. configurable: true
  78096. });
  78097. Object.defineProperty(Bone.prototype, "rotation", {
  78098. /** Gets or sets current rotation (in local space) */
  78099. get: function () {
  78100. return this.getRotation();
  78101. },
  78102. set: function (newRotation) {
  78103. this.setRotation(newRotation);
  78104. },
  78105. enumerable: true,
  78106. configurable: true
  78107. });
  78108. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78109. /** Gets or sets current rotation quaternion (in local space) */
  78110. get: function () {
  78111. this._decompose();
  78112. return this._localRotation;
  78113. },
  78114. set: function (newRotation) {
  78115. this.setRotationQuaternion(newRotation);
  78116. },
  78117. enumerable: true,
  78118. configurable: true
  78119. });
  78120. Object.defineProperty(Bone.prototype, "scaling", {
  78121. /** Gets or sets current scaling (in local space) */
  78122. get: function () {
  78123. return this.getScale();
  78124. },
  78125. set: function (newScaling) {
  78126. this.setScale(newScaling);
  78127. },
  78128. enumerable: true,
  78129. configurable: true
  78130. });
  78131. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78132. /**
  78133. * Gets the animation properties override
  78134. */
  78135. get: function () {
  78136. return this._skeleton.animationPropertiesOverride;
  78137. },
  78138. enumerable: true,
  78139. configurable: true
  78140. });
  78141. // Methods
  78142. Bone.prototype._decompose = function () {
  78143. if (!this._needToDecompose) {
  78144. return;
  78145. }
  78146. this._needToDecompose = false;
  78147. if (!this._localScaling) {
  78148. this._localScaling = BABYLON.Vector3.Zero();
  78149. this._localRotation = BABYLON.Quaternion.Zero();
  78150. this._localPosition = BABYLON.Vector3.Zero();
  78151. }
  78152. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78153. };
  78154. Bone.prototype._compose = function () {
  78155. if (!this._needToCompose) {
  78156. return;
  78157. }
  78158. this._needToCompose = false;
  78159. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78160. };
  78161. /**
  78162. * Update the base and local matrices
  78163. * @param matrix defines the new base or local matrix
  78164. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78165. * @param updateLocalMatrix defines if the local matrix should be updated
  78166. */
  78167. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78168. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78169. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78170. this._baseMatrix.copyFrom(matrix);
  78171. if (updateDifferenceMatrix) {
  78172. this._updateDifferenceMatrix();
  78173. }
  78174. if (updateLocalMatrix) {
  78175. this._localMatrix.copyFrom(matrix);
  78176. this._markAsDirtyAndDecompose();
  78177. }
  78178. else {
  78179. this.markAsDirty();
  78180. }
  78181. };
  78182. /** @hidden */
  78183. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78184. if (updateChildren === void 0) { updateChildren = true; }
  78185. if (!rootMatrix) {
  78186. rootMatrix = this._baseMatrix;
  78187. }
  78188. if (this._parent) {
  78189. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78190. }
  78191. else {
  78192. this._absoluteTransform.copyFrom(rootMatrix);
  78193. }
  78194. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78195. if (updateChildren) {
  78196. for (var index = 0; index < this.children.length; index++) {
  78197. this.children[index]._updateDifferenceMatrix();
  78198. }
  78199. }
  78200. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78201. };
  78202. /**
  78203. * Flag the bone as dirty (Forcing it to update everything)
  78204. */
  78205. Bone.prototype.markAsDirty = function () {
  78206. this._currentRenderId++;
  78207. this._childRenderId++;
  78208. this._skeleton._markAsDirty();
  78209. };
  78210. Bone.prototype._markAsDirtyAndCompose = function () {
  78211. this.markAsDirty();
  78212. this._needToCompose = true;
  78213. };
  78214. Bone.prototype._markAsDirtyAndDecompose = function () {
  78215. this.markAsDirty();
  78216. this._needToDecompose = true;
  78217. };
  78218. /**
  78219. * Copy an animation range from another bone
  78220. * @param source defines the source bone
  78221. * @param rangeName defines the range name to copy
  78222. * @param frameOffset defines the frame offset
  78223. * @param rescaleAsRequired defines if rescaling must be applied if required
  78224. * @param skelDimensionsRatio defines the scaling ratio
  78225. * @returns true if operation was successful
  78226. */
  78227. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78228. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78229. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78230. // all animation may be coming from a library skeleton, so may need to create animation
  78231. if (this.animations.length === 0) {
  78232. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78233. this.animations[0].setKeys([]);
  78234. }
  78235. // get animation info / verify there is such a range from the source bone
  78236. var sourceRange = source.animations[0].getRange(rangeName);
  78237. if (!sourceRange) {
  78238. return false;
  78239. }
  78240. var from = sourceRange.from;
  78241. var to = sourceRange.to;
  78242. var sourceKeys = source.animations[0].getKeys();
  78243. // rescaling prep
  78244. var sourceBoneLength = source.length;
  78245. var sourceParent = source.getParent();
  78246. var parent = this.getParent();
  78247. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78248. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78249. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78250. var destKeys = this.animations[0].getKeys();
  78251. // loop vars declaration
  78252. var orig;
  78253. var origTranslation;
  78254. var mat;
  78255. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78256. orig = sourceKeys[key];
  78257. if (orig.frame >= from && orig.frame <= to) {
  78258. if (rescaleAsRequired) {
  78259. mat = orig.value.clone();
  78260. // scale based on parent ratio, when bone has parent
  78261. if (parentScalingReqd) {
  78262. origTranslation = mat.getTranslation();
  78263. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78264. // scale based on skeleton dimension ratio when root bone, and value is passed
  78265. }
  78266. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78267. origTranslation = mat.getTranslation();
  78268. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78269. // use original when root bone, and no data for skelDimensionsRatio
  78270. }
  78271. else {
  78272. mat = orig.value;
  78273. }
  78274. }
  78275. else {
  78276. mat = orig.value;
  78277. }
  78278. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78279. }
  78280. }
  78281. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78282. return true;
  78283. };
  78284. /**
  78285. * Translate the bone in local or world space
  78286. * @param vec The amount to translate the bone
  78287. * @param space The space that the translation is in
  78288. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78289. */
  78290. Bone.prototype.translate = function (vec, space, mesh) {
  78291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78292. var lm = this.getLocalMatrix();
  78293. if (space == BABYLON.Space.LOCAL) {
  78294. lm.m[12] += vec.x;
  78295. lm.m[13] += vec.y;
  78296. lm.m[14] += vec.z;
  78297. }
  78298. else {
  78299. var wm = null;
  78300. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78301. if (mesh) {
  78302. wm = mesh.getWorldMatrix();
  78303. }
  78304. this._skeleton.computeAbsoluteTransforms();
  78305. var tmat = Bone._tmpMats[0];
  78306. var tvec = Bone._tmpVecs[0];
  78307. if (this._parent) {
  78308. if (mesh && wm) {
  78309. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78310. tmat.multiplyToRef(wm, tmat);
  78311. }
  78312. else {
  78313. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78314. }
  78315. }
  78316. tmat.m[12] = 0;
  78317. tmat.m[13] = 0;
  78318. tmat.m[14] = 0;
  78319. tmat.invert();
  78320. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78321. lm.m[12] += tvec.x;
  78322. lm.m[13] += tvec.y;
  78323. lm.m[14] += tvec.z;
  78324. }
  78325. this._markAsDirtyAndDecompose();
  78326. };
  78327. /**
  78328. * Set the postion of the bone in local or world space
  78329. * @param position The position to set the bone
  78330. * @param space The space that the position is in
  78331. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78332. */
  78333. Bone.prototype.setPosition = function (position, space, mesh) {
  78334. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78335. var lm = this.getLocalMatrix();
  78336. if (space == BABYLON.Space.LOCAL) {
  78337. lm.m[12] = position.x;
  78338. lm.m[13] = position.y;
  78339. lm.m[14] = position.z;
  78340. }
  78341. else {
  78342. var wm = null;
  78343. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78344. if (mesh) {
  78345. wm = mesh.getWorldMatrix();
  78346. }
  78347. this._skeleton.computeAbsoluteTransforms();
  78348. var tmat = Bone._tmpMats[0];
  78349. var vec = Bone._tmpVecs[0];
  78350. if (this._parent) {
  78351. if (mesh && wm) {
  78352. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78353. tmat.multiplyToRef(wm, tmat);
  78354. }
  78355. else {
  78356. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78357. }
  78358. }
  78359. tmat.invert();
  78360. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78361. lm.m[12] = vec.x;
  78362. lm.m[13] = vec.y;
  78363. lm.m[14] = vec.z;
  78364. }
  78365. this._markAsDirtyAndDecompose();
  78366. };
  78367. /**
  78368. * Set the absolute position of the bone (world space)
  78369. * @param position The position to set the bone
  78370. * @param mesh The mesh that this bone is attached to
  78371. */
  78372. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78373. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78374. };
  78375. /**
  78376. * Scale the bone on the x, y and z axes (in local space)
  78377. * @param x The amount to scale the bone on the x axis
  78378. * @param y The amount to scale the bone on the y axis
  78379. * @param z The amount to scale the bone on the z axis
  78380. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78381. */
  78382. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78383. if (scaleChildren === void 0) { scaleChildren = false; }
  78384. var locMat = this.getLocalMatrix();
  78385. // Apply new scaling on top of current local matrix
  78386. var scaleMat = Bone._tmpMats[0];
  78387. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78388. scaleMat.multiplyToRef(locMat, locMat);
  78389. // Invert scaling matrix and apply the inverse to all children
  78390. scaleMat.invert();
  78391. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78392. var child = _a[_i];
  78393. var cm = child.getLocalMatrix();
  78394. cm.multiplyToRef(scaleMat, cm);
  78395. cm.m[12] *= x;
  78396. cm.m[13] *= y;
  78397. cm.m[14] *= z;
  78398. child._markAsDirtyAndDecompose();
  78399. }
  78400. this._markAsDirtyAndDecompose();
  78401. if (scaleChildren) {
  78402. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78403. var child = _c[_b];
  78404. child.scale(x, y, z, scaleChildren);
  78405. }
  78406. }
  78407. };
  78408. /**
  78409. * Set the bone scaling in local space
  78410. * @param scale defines the scaling vector
  78411. */
  78412. Bone.prototype.setScale = function (scale) {
  78413. this._decompose();
  78414. this._localScaling.copyFrom(scale);
  78415. this._markAsDirtyAndCompose();
  78416. };
  78417. /**
  78418. * Gets the current scaling in local space
  78419. * @returns the current scaling vector
  78420. */
  78421. Bone.prototype.getScale = function () {
  78422. this._decompose();
  78423. return this._localScaling;
  78424. };
  78425. /**
  78426. * Gets the current scaling in local space and stores it in a target vector
  78427. * @param result defines the target vector
  78428. */
  78429. Bone.prototype.getScaleToRef = function (result) {
  78430. this._decompose();
  78431. result.copyFrom(this._localScaling);
  78432. };
  78433. /**
  78434. * Set the yaw, pitch, and roll of the bone in local or world space
  78435. * @param yaw The rotation of the bone on the y axis
  78436. * @param pitch The rotation of the bone on the x axis
  78437. * @param roll The rotation of the bone on the z axis
  78438. * @param space The space that the axes of rotation are in
  78439. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78440. */
  78441. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78442. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78443. if (space === BABYLON.Space.LOCAL) {
  78444. var quat = Bone._tmpQuat;
  78445. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78446. this.setRotationQuaternion(quat, space, mesh);
  78447. return;
  78448. }
  78449. var rotMatInv = Bone._tmpMats[0];
  78450. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78451. return;
  78452. }
  78453. var rotMat = Bone._tmpMats[1];
  78454. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78455. rotMatInv.multiplyToRef(rotMat, rotMat);
  78456. this._rotateWithMatrix(rotMat, space, mesh);
  78457. };
  78458. /**
  78459. * Add a rotation to the bone on an axis in local or world space
  78460. * @param axis The axis to rotate the bone on
  78461. * @param amount The amount to rotate the bone
  78462. * @param space The space that the axis is in
  78463. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78464. */
  78465. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78466. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78467. var rmat = Bone._tmpMats[0];
  78468. rmat.m[12] = 0;
  78469. rmat.m[13] = 0;
  78470. rmat.m[14] = 0;
  78471. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78472. this._rotateWithMatrix(rmat, space, mesh);
  78473. };
  78474. /**
  78475. * Set the rotation of the bone to a particular axis angle in local or world space
  78476. * @param axis The axis to rotate the bone on
  78477. * @param angle The angle that the bone should be rotated to
  78478. * @param space The space that the axis is in
  78479. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78480. */
  78481. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78482. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78483. if (space === BABYLON.Space.LOCAL) {
  78484. var quat = Bone._tmpQuat;
  78485. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78486. this.setRotationQuaternion(quat, space, mesh);
  78487. return;
  78488. }
  78489. var rotMatInv = Bone._tmpMats[0];
  78490. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78491. return;
  78492. }
  78493. var rotMat = Bone._tmpMats[1];
  78494. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78495. rotMatInv.multiplyToRef(rotMat, rotMat);
  78496. this._rotateWithMatrix(rotMat, space, mesh);
  78497. };
  78498. /**
  78499. * Set the euler rotation of the bone in local of world space
  78500. * @param rotation The euler rotation that the bone should be set to
  78501. * @param space The space that the rotation is in
  78502. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78503. */
  78504. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78505. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78506. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78507. };
  78508. /**
  78509. * Set the quaternion rotation of the bone in local of world space
  78510. * @param quat The quaternion rotation that the bone should be set to
  78511. * @param space The space that the rotation is in
  78512. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78513. */
  78514. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78515. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78516. if (space === BABYLON.Space.LOCAL) {
  78517. this._decompose();
  78518. this._localRotation.copyFrom(quat);
  78519. this._markAsDirtyAndCompose();
  78520. return;
  78521. }
  78522. var rotMatInv = Bone._tmpMats[0];
  78523. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78524. return;
  78525. }
  78526. var rotMat = Bone._tmpMats[1];
  78527. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78528. rotMatInv.multiplyToRef(rotMat, rotMat);
  78529. this._rotateWithMatrix(rotMat, space, mesh);
  78530. };
  78531. /**
  78532. * Set the rotation matrix of the bone in local of world space
  78533. * @param rotMat The rotation matrix that the bone should be set to
  78534. * @param space The space that the rotation is in
  78535. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78536. */
  78537. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78538. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78539. if (space === BABYLON.Space.LOCAL) {
  78540. var quat = Bone._tmpQuat;
  78541. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78542. this.setRotationQuaternion(quat, space, mesh);
  78543. return;
  78544. }
  78545. var rotMatInv = Bone._tmpMats[0];
  78546. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78547. return;
  78548. }
  78549. var rotMat2 = Bone._tmpMats[1];
  78550. rotMat2.copyFrom(rotMat);
  78551. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78552. this._rotateWithMatrix(rotMat2, space, mesh);
  78553. };
  78554. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78555. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78556. var lmat = this.getLocalMatrix();
  78557. var lx = lmat.m[12];
  78558. var ly = lmat.m[13];
  78559. var lz = lmat.m[14];
  78560. var parent = this.getParent();
  78561. var parentScale = Bone._tmpMats[3];
  78562. var parentScaleInv = Bone._tmpMats[4];
  78563. if (parent && space == BABYLON.Space.WORLD) {
  78564. if (mesh) {
  78565. parentScale.copyFrom(mesh.getWorldMatrix());
  78566. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78567. }
  78568. else {
  78569. parentScale.copyFrom(parent.getAbsoluteTransform());
  78570. }
  78571. parentScaleInv.copyFrom(parentScale);
  78572. parentScaleInv.invert();
  78573. lmat.multiplyToRef(parentScale, lmat);
  78574. lmat.multiplyToRef(rmat, lmat);
  78575. lmat.multiplyToRef(parentScaleInv, lmat);
  78576. }
  78577. else {
  78578. if (space == BABYLON.Space.WORLD && mesh) {
  78579. parentScale.copyFrom(mesh.getWorldMatrix());
  78580. parentScaleInv.copyFrom(parentScale);
  78581. parentScaleInv.invert();
  78582. lmat.multiplyToRef(parentScale, lmat);
  78583. lmat.multiplyToRef(rmat, lmat);
  78584. lmat.multiplyToRef(parentScaleInv, lmat);
  78585. }
  78586. else {
  78587. lmat.multiplyToRef(rmat, lmat);
  78588. }
  78589. }
  78590. lmat.m[12] = lx;
  78591. lmat.m[13] = ly;
  78592. lmat.m[14] = lz;
  78593. this.computeAbsoluteTransforms();
  78594. this._markAsDirtyAndDecompose();
  78595. };
  78596. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78597. var scaleMatrix = Bone._tmpMats[2];
  78598. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78599. if (mesh) {
  78600. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78601. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78602. }
  78603. rotMatInv.invert();
  78604. if (isNaN(rotMatInv.m[0])) {
  78605. // Matrix failed to invert.
  78606. // This can happen if scale is zero for example.
  78607. return false;
  78608. }
  78609. scaleMatrix.m[0] *= this._scalingDeterminant;
  78610. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78611. return true;
  78612. };
  78613. /**
  78614. * Get the position of the bone in local or world space
  78615. * @param space The space that the returned position is in
  78616. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78617. * @returns The position of the bone
  78618. */
  78619. Bone.prototype.getPosition = function (space, mesh) {
  78620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78621. if (mesh === void 0) { mesh = null; }
  78622. var pos = BABYLON.Vector3.Zero();
  78623. this.getPositionToRef(space, mesh, pos);
  78624. return pos;
  78625. };
  78626. /**
  78627. * Copy the position of the bone to a vector3 in local or world space
  78628. * @param space The space that the returned position is in
  78629. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78630. * @param result The vector3 to copy the position to
  78631. */
  78632. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78633. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78634. if (space == BABYLON.Space.LOCAL) {
  78635. var lm = this.getLocalMatrix();
  78636. result.x = lm.m[12];
  78637. result.y = lm.m[13];
  78638. result.z = lm.m[14];
  78639. }
  78640. else {
  78641. var wm = null;
  78642. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78643. if (mesh) {
  78644. wm = mesh.getWorldMatrix();
  78645. }
  78646. this._skeleton.computeAbsoluteTransforms();
  78647. var tmat = Bone._tmpMats[0];
  78648. if (mesh && wm) {
  78649. tmat.copyFrom(this.getAbsoluteTransform());
  78650. tmat.multiplyToRef(wm, tmat);
  78651. }
  78652. else {
  78653. tmat = this.getAbsoluteTransform();
  78654. }
  78655. result.x = tmat.m[12];
  78656. result.y = tmat.m[13];
  78657. result.z = tmat.m[14];
  78658. }
  78659. };
  78660. /**
  78661. * Get the absolute position of the bone (world space)
  78662. * @param mesh The mesh that this bone is attached to
  78663. * @returns The absolute position of the bone
  78664. */
  78665. Bone.prototype.getAbsolutePosition = function (mesh) {
  78666. if (mesh === void 0) { mesh = null; }
  78667. var pos = BABYLON.Vector3.Zero();
  78668. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78669. return pos;
  78670. };
  78671. /**
  78672. * Copy the absolute position of the bone (world space) to the result param
  78673. * @param mesh The mesh that this bone is attached to
  78674. * @param result The vector3 to copy the absolute position to
  78675. */
  78676. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78677. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78678. };
  78679. /**
  78680. * Compute the absolute transforms of this bone and its children
  78681. */
  78682. Bone.prototype.computeAbsoluteTransforms = function () {
  78683. this._compose();
  78684. if (this._parent) {
  78685. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78686. }
  78687. else {
  78688. this._absoluteTransform.copyFrom(this._localMatrix);
  78689. var poseMatrix = this._skeleton.getPoseMatrix();
  78690. if (poseMatrix) {
  78691. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78692. }
  78693. }
  78694. var children = this.children;
  78695. var len = children.length;
  78696. for (var i = 0; i < len; i++) {
  78697. children[i].computeAbsoluteTransforms();
  78698. }
  78699. };
  78700. /**
  78701. * Get the world direction from an axis that is in the local space of the bone
  78702. * @param localAxis The local direction that is used to compute the world direction
  78703. * @param mesh The mesh that this bone is attached to
  78704. * @returns The world direction
  78705. */
  78706. Bone.prototype.getDirection = function (localAxis, mesh) {
  78707. if (mesh === void 0) { mesh = null; }
  78708. var result = BABYLON.Vector3.Zero();
  78709. this.getDirectionToRef(localAxis, mesh, result);
  78710. return result;
  78711. };
  78712. /**
  78713. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78714. * @param localAxis The local direction that is used to compute the world direction
  78715. * @param mesh The mesh that this bone is attached to
  78716. * @param result The vector3 that the world direction will be copied to
  78717. */
  78718. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78719. if (mesh === void 0) { mesh = null; }
  78720. var wm = null;
  78721. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78722. if (mesh) {
  78723. wm = mesh.getWorldMatrix();
  78724. }
  78725. this._skeleton.computeAbsoluteTransforms();
  78726. var mat = Bone._tmpMats[0];
  78727. mat.copyFrom(this.getAbsoluteTransform());
  78728. if (mesh && wm) {
  78729. mat.multiplyToRef(wm, mat);
  78730. }
  78731. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78732. result.normalize();
  78733. };
  78734. /**
  78735. * Get the euler rotation of the bone in local or world space
  78736. * @param space The space that the rotation should be in
  78737. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78738. * @returns The euler rotation
  78739. */
  78740. Bone.prototype.getRotation = function (space, mesh) {
  78741. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78742. if (mesh === void 0) { mesh = null; }
  78743. var result = BABYLON.Vector3.Zero();
  78744. this.getRotationToRef(space, mesh, result);
  78745. return result;
  78746. };
  78747. /**
  78748. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78749. * @param space The space that the rotation should be in
  78750. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78751. * @param result The vector3 that the rotation should be copied to
  78752. */
  78753. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78754. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78755. if (mesh === void 0) { mesh = null; }
  78756. var quat = Bone._tmpQuat;
  78757. this.getRotationQuaternionToRef(space, mesh, quat);
  78758. quat.toEulerAnglesToRef(result);
  78759. };
  78760. /**
  78761. * Get the quaternion rotation of the bone in either local or world space
  78762. * @param space The space that the rotation should be in
  78763. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78764. * @returns The quaternion rotation
  78765. */
  78766. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78768. if (mesh === void 0) { mesh = null; }
  78769. var result = BABYLON.Quaternion.Identity();
  78770. this.getRotationQuaternionToRef(space, mesh, result);
  78771. return result;
  78772. };
  78773. /**
  78774. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78775. * @param space The space that the rotation should be in
  78776. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78777. * @param result The quaternion that the rotation should be copied to
  78778. */
  78779. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78780. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78781. if (mesh === void 0) { mesh = null; }
  78782. if (space == BABYLON.Space.LOCAL) {
  78783. this._decompose();
  78784. result.copyFrom(this._localRotation);
  78785. }
  78786. else {
  78787. var mat = Bone._tmpMats[0];
  78788. var amat = this.getAbsoluteTransform();
  78789. if (mesh) {
  78790. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78791. }
  78792. else {
  78793. mat.copyFrom(amat);
  78794. }
  78795. mat.m[0] *= this._scalingDeterminant;
  78796. mat.m[1] *= this._scalingDeterminant;
  78797. mat.m[2] *= this._scalingDeterminant;
  78798. mat.decompose(undefined, result, undefined);
  78799. }
  78800. };
  78801. /**
  78802. * Get the rotation matrix of the bone in local or world space
  78803. * @param space The space that the rotation should be in
  78804. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78805. * @returns The rotation matrix
  78806. */
  78807. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78808. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78809. var result = BABYLON.Matrix.Identity();
  78810. this.getRotationMatrixToRef(space, mesh, result);
  78811. return result;
  78812. };
  78813. /**
  78814. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78815. * @param space The space that the rotation should be in
  78816. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78817. * @param result The quaternion that the rotation should be copied to
  78818. */
  78819. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78820. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78821. if (space == BABYLON.Space.LOCAL) {
  78822. this.getLocalMatrix().getRotationMatrixToRef(result);
  78823. }
  78824. else {
  78825. var mat = Bone._tmpMats[0];
  78826. var amat = this.getAbsoluteTransform();
  78827. if (mesh) {
  78828. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78829. }
  78830. else {
  78831. mat.copyFrom(amat);
  78832. }
  78833. mat.m[0] *= this._scalingDeterminant;
  78834. mat.m[1] *= this._scalingDeterminant;
  78835. mat.m[2] *= this._scalingDeterminant;
  78836. mat.getRotationMatrixToRef(result);
  78837. }
  78838. };
  78839. /**
  78840. * Get the world position of a point that is in the local space of the bone
  78841. * @param position The local position
  78842. * @param mesh The mesh that this bone is attached to
  78843. * @returns The world position
  78844. */
  78845. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78846. if (mesh === void 0) { mesh = null; }
  78847. var result = BABYLON.Vector3.Zero();
  78848. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78849. return result;
  78850. };
  78851. /**
  78852. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78853. * @param position The local position
  78854. * @param mesh The mesh that this bone is attached to
  78855. * @param result The vector3 that the world position should be copied to
  78856. */
  78857. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78858. if (mesh === void 0) { mesh = null; }
  78859. var wm = null;
  78860. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78861. if (mesh) {
  78862. wm = mesh.getWorldMatrix();
  78863. }
  78864. this._skeleton.computeAbsoluteTransforms();
  78865. var tmat = Bone._tmpMats[0];
  78866. if (mesh && wm) {
  78867. tmat.copyFrom(this.getAbsoluteTransform());
  78868. tmat.multiplyToRef(wm, tmat);
  78869. }
  78870. else {
  78871. tmat = this.getAbsoluteTransform();
  78872. }
  78873. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78874. };
  78875. /**
  78876. * Get the local position of a point that is in world space
  78877. * @param position The world position
  78878. * @param mesh The mesh that this bone is attached to
  78879. * @returns The local position
  78880. */
  78881. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78882. if (mesh === void 0) { mesh = null; }
  78883. var result = BABYLON.Vector3.Zero();
  78884. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78885. return result;
  78886. };
  78887. /**
  78888. * Get the local position of a point that is in world space and copy it to the result param
  78889. * @param position The world position
  78890. * @param mesh The mesh that this bone is attached to
  78891. * @param result The vector3 that the local position should be copied to
  78892. */
  78893. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78894. if (mesh === void 0) { mesh = null; }
  78895. var wm = null;
  78896. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78897. if (mesh) {
  78898. wm = mesh.getWorldMatrix();
  78899. }
  78900. this._skeleton.computeAbsoluteTransforms();
  78901. var tmat = Bone._tmpMats[0];
  78902. tmat.copyFrom(this.getAbsoluteTransform());
  78903. if (mesh && wm) {
  78904. tmat.multiplyToRef(wm, tmat);
  78905. }
  78906. tmat.invert();
  78907. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78908. };
  78909. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78910. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78911. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78912. return Bone;
  78913. }(BABYLON.Node));
  78914. BABYLON.Bone = Bone;
  78915. })(BABYLON || (BABYLON = {}));
  78916. //# sourceMappingURL=babylon.bone.js.map
  78917. var BABYLON;
  78918. (function (BABYLON) {
  78919. /**
  78920. * Class used to apply inverse kinematics to bones
  78921. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78922. */
  78923. var BoneIKController = /** @class */ (function () {
  78924. /**
  78925. * Creates a new BoneIKController
  78926. * @param mesh defines the mesh to control
  78927. * @param bone defines the bone to control
  78928. * @param options defines options to set up the controller
  78929. */
  78930. function BoneIKController(mesh, bone, options) {
  78931. /**
  78932. * Gets or sets the target position
  78933. */
  78934. this.targetPosition = BABYLON.Vector3.Zero();
  78935. /**
  78936. * Gets or sets the pole target position
  78937. */
  78938. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78939. /**
  78940. * Gets or sets the pole target local offset
  78941. */
  78942. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78943. /**
  78944. * Gets or sets the pole angle
  78945. */
  78946. this.poleAngle = 0;
  78947. /**
  78948. * 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)
  78949. */
  78950. this.slerpAmount = 1;
  78951. this._bone1Quat = BABYLON.Quaternion.Identity();
  78952. this._bone1Mat = BABYLON.Matrix.Identity();
  78953. this._bone2Ang = Math.PI;
  78954. this._maxAngle = Math.PI;
  78955. this._rightHandedSystem = false;
  78956. this._bendAxis = BABYLON.Vector3.Right();
  78957. this._slerping = false;
  78958. this._adjustRoll = 0;
  78959. this._bone2 = bone;
  78960. this._bone1 = bone.getParent();
  78961. if (!this._bone1) {
  78962. return;
  78963. }
  78964. this.mesh = mesh;
  78965. var bonePos = bone.getPosition();
  78966. if (bone.getAbsoluteTransform().determinant() > 0) {
  78967. this._rightHandedSystem = true;
  78968. this._bendAxis.x = 0;
  78969. this._bendAxis.y = 0;
  78970. this._bendAxis.z = -1;
  78971. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78972. this._adjustRoll = Math.PI * .5;
  78973. this._bendAxis.z = 1;
  78974. }
  78975. }
  78976. if (this._bone1.length) {
  78977. var boneScale1 = this._bone1.getScale();
  78978. var boneScale2 = this._bone2.getScale();
  78979. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78980. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78981. }
  78982. else if (this._bone1.children[0]) {
  78983. mesh.computeWorldMatrix(true);
  78984. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78985. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78986. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78987. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78988. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78989. }
  78990. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78991. this.maxAngle = Math.PI;
  78992. if (options) {
  78993. if (options.targetMesh) {
  78994. this.targetMesh = options.targetMesh;
  78995. this.targetMesh.computeWorldMatrix(true);
  78996. }
  78997. if (options.poleTargetMesh) {
  78998. this.poleTargetMesh = options.poleTargetMesh;
  78999. this.poleTargetMesh.computeWorldMatrix(true);
  79000. }
  79001. else if (options.poleTargetBone) {
  79002. this.poleTargetBone = options.poleTargetBone;
  79003. }
  79004. else if (this._bone1.getParent()) {
  79005. this.poleTargetBone = this._bone1.getParent();
  79006. }
  79007. if (options.poleTargetLocalOffset) {
  79008. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79009. }
  79010. if (options.poleAngle) {
  79011. this.poleAngle = options.poleAngle;
  79012. }
  79013. if (options.bendAxis) {
  79014. this._bendAxis.copyFrom(options.bendAxis);
  79015. }
  79016. if (options.maxAngle) {
  79017. this.maxAngle = options.maxAngle;
  79018. }
  79019. if (options.slerpAmount) {
  79020. this.slerpAmount = options.slerpAmount;
  79021. }
  79022. }
  79023. }
  79024. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79025. /**
  79026. * Gets or sets maximum allowed angle
  79027. */
  79028. get: function () {
  79029. return this._maxAngle;
  79030. },
  79031. set: function (value) {
  79032. this._setMaxAngle(value);
  79033. },
  79034. enumerable: true,
  79035. configurable: true
  79036. });
  79037. BoneIKController.prototype._setMaxAngle = function (ang) {
  79038. if (ang < 0) {
  79039. ang = 0;
  79040. }
  79041. if (ang > Math.PI || ang == undefined) {
  79042. ang = Math.PI;
  79043. }
  79044. this._maxAngle = ang;
  79045. var a = this._bone1Length;
  79046. var b = this._bone2Length;
  79047. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79048. };
  79049. /**
  79050. * Force the controller to update the bones
  79051. */
  79052. BoneIKController.prototype.update = function () {
  79053. var bone1 = this._bone1;
  79054. if (!bone1) {
  79055. return;
  79056. }
  79057. var target = this.targetPosition;
  79058. var poleTarget = this.poleTargetPosition;
  79059. var mat1 = BoneIKController._tmpMats[0];
  79060. var mat2 = BoneIKController._tmpMats[1];
  79061. if (this.targetMesh) {
  79062. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79063. }
  79064. if (this.poleTargetBone) {
  79065. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79066. }
  79067. else if (this.poleTargetMesh) {
  79068. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79069. }
  79070. var bonePos = BoneIKController._tmpVecs[0];
  79071. var zaxis = BoneIKController._tmpVecs[1];
  79072. var xaxis = BoneIKController._tmpVecs[2];
  79073. var yaxis = BoneIKController._tmpVecs[3];
  79074. var upAxis = BoneIKController._tmpVecs[4];
  79075. var _tmpQuat = BoneIKController._tmpQuat;
  79076. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79077. poleTarget.subtractToRef(bonePos, upAxis);
  79078. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79079. upAxis.y = 1;
  79080. }
  79081. else {
  79082. upAxis.normalize();
  79083. }
  79084. target.subtractToRef(bonePos, yaxis);
  79085. yaxis.normalize();
  79086. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79087. zaxis.normalize();
  79088. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79089. xaxis.normalize();
  79090. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79091. var a = this._bone1Length;
  79092. var b = this._bone2Length;
  79093. var c = BABYLON.Vector3.Distance(bonePos, target);
  79094. if (this._maxReach > 0) {
  79095. c = Math.min(this._maxReach, c);
  79096. }
  79097. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79098. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79099. if (acosa > 1) {
  79100. acosa = 1;
  79101. }
  79102. if (acosb > 1) {
  79103. acosb = 1;
  79104. }
  79105. if (acosa < -1) {
  79106. acosa = -1;
  79107. }
  79108. if (acosb < -1) {
  79109. acosb = -1;
  79110. }
  79111. var angA = Math.acos(acosa);
  79112. var angB = Math.acos(acosb);
  79113. var angC = -angA - angB;
  79114. if (this._rightHandedSystem) {
  79115. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79116. mat2.multiplyToRef(mat1, mat1);
  79117. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79118. mat2.multiplyToRef(mat1, mat1);
  79119. }
  79120. else {
  79121. var _tmpVec = BoneIKController._tmpVecs[5];
  79122. _tmpVec.copyFrom(this._bendAxis);
  79123. _tmpVec.x *= -1;
  79124. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79125. mat2.multiplyToRef(mat1, mat1);
  79126. }
  79127. if (this.poleAngle) {
  79128. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79129. mat1.multiplyToRef(mat2, mat1);
  79130. }
  79131. if (this._bone1) {
  79132. if (this.slerpAmount < 1) {
  79133. if (!this._slerping) {
  79134. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79135. }
  79136. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79137. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79138. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79139. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79140. this._slerping = true;
  79141. }
  79142. else {
  79143. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79144. this._bone1Mat.copyFrom(mat1);
  79145. this._slerping = false;
  79146. }
  79147. }
  79148. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79149. this._bone2Ang = angC;
  79150. };
  79151. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79152. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79153. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79154. return BoneIKController;
  79155. }());
  79156. BABYLON.BoneIKController = BoneIKController;
  79157. })(BABYLON || (BABYLON = {}));
  79158. //# sourceMappingURL=babylon.boneIKController.js.map
  79159. var BABYLON;
  79160. (function (BABYLON) {
  79161. /**
  79162. * Class used to make a bone look toward a point in space
  79163. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79164. */
  79165. var BoneLookController = /** @class */ (function () {
  79166. /**
  79167. * Create a BoneLookController
  79168. * @param mesh the mesh that the bone belongs to
  79169. * @param bone the bone that will be looking to the target
  79170. * @param target the target Vector3 to look at
  79171. * @param settings optional settings:
  79172. * * maxYaw: the maximum angle the bone will yaw to
  79173. * * minYaw: the minimum angle the bone will yaw to
  79174. * * maxPitch: the maximum angle the bone will pitch to
  79175. * * minPitch: the minimum angle the bone will yaw to
  79176. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79177. * * upAxis: the up axis of the coordinate system
  79178. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79179. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79180. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79181. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79182. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79183. * * adjustRoll: used to make an adjustment to the roll of the bone
  79184. **/
  79185. function BoneLookController(mesh, bone, target, options) {
  79186. /**
  79187. * The up axis of the coordinate system that is used when the bone is rotated
  79188. */
  79189. this.upAxis = BABYLON.Vector3.Up();
  79190. /**
  79191. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79192. */
  79193. this.upAxisSpace = BABYLON.Space.LOCAL;
  79194. /**
  79195. * Used to make an adjustment to the yaw of the bone
  79196. */
  79197. this.adjustYaw = 0;
  79198. /**
  79199. * Used to make an adjustment to the pitch of the bone
  79200. */
  79201. this.adjustPitch = 0;
  79202. /**
  79203. * Used to make an adjustment to the roll of the bone
  79204. */
  79205. this.adjustRoll = 0;
  79206. /**
  79207. * 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)
  79208. */
  79209. this.slerpAmount = 1;
  79210. this._boneQuat = BABYLON.Quaternion.Identity();
  79211. this._slerping = false;
  79212. this._firstFrameSkipped = false;
  79213. this._fowardAxis = BABYLON.Vector3.Forward();
  79214. this.mesh = mesh;
  79215. this.bone = bone;
  79216. this.target = target;
  79217. if (options) {
  79218. if (options.adjustYaw) {
  79219. this.adjustYaw = options.adjustYaw;
  79220. }
  79221. if (options.adjustPitch) {
  79222. this.adjustPitch = options.adjustPitch;
  79223. }
  79224. if (options.adjustRoll) {
  79225. this.adjustRoll = options.adjustRoll;
  79226. }
  79227. if (options.maxYaw != null) {
  79228. this.maxYaw = options.maxYaw;
  79229. }
  79230. else {
  79231. this.maxYaw = Math.PI;
  79232. }
  79233. if (options.minYaw != null) {
  79234. this.minYaw = options.minYaw;
  79235. }
  79236. else {
  79237. this.minYaw = -Math.PI;
  79238. }
  79239. if (options.maxPitch != null) {
  79240. this.maxPitch = options.maxPitch;
  79241. }
  79242. else {
  79243. this.maxPitch = Math.PI;
  79244. }
  79245. if (options.minPitch != null) {
  79246. this.minPitch = options.minPitch;
  79247. }
  79248. else {
  79249. this.minPitch = -Math.PI;
  79250. }
  79251. if (options.slerpAmount != null) {
  79252. this.slerpAmount = options.slerpAmount;
  79253. }
  79254. if (options.upAxis != null) {
  79255. this.upAxis = options.upAxis;
  79256. }
  79257. if (options.upAxisSpace != null) {
  79258. this.upAxisSpace = options.upAxisSpace;
  79259. }
  79260. if (options.yawAxis != null || options.pitchAxis != null) {
  79261. var newYawAxis = BABYLON.Axis.Y;
  79262. var newPitchAxis = BABYLON.Axis.X;
  79263. if (options.yawAxis != null) {
  79264. newYawAxis = options.yawAxis.clone();
  79265. newYawAxis.normalize();
  79266. }
  79267. if (options.pitchAxis != null) {
  79268. newPitchAxis = options.pitchAxis.clone();
  79269. newPitchAxis.normalize();
  79270. }
  79271. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79272. this._transformYawPitch = BABYLON.Matrix.Identity();
  79273. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79274. this._transformYawPitchInv = this._transformYawPitch.clone();
  79275. this._transformYawPitch.invert();
  79276. }
  79277. }
  79278. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79279. this.upAxisSpace = BABYLON.Space.LOCAL;
  79280. }
  79281. }
  79282. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79283. /**
  79284. * Gets or sets the minimum yaw angle that the bone can look to
  79285. */
  79286. get: function () {
  79287. return this._minYaw;
  79288. },
  79289. set: function (value) {
  79290. this._minYaw = value;
  79291. this._minYawSin = Math.sin(value);
  79292. this._minYawCos = Math.cos(value);
  79293. if (this._maxYaw != null) {
  79294. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79295. this._yawRange = this._maxYaw - this._minYaw;
  79296. }
  79297. },
  79298. enumerable: true,
  79299. configurable: true
  79300. });
  79301. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79302. /**
  79303. * Gets or sets the maximum yaw angle that the bone can look to
  79304. */
  79305. get: function () {
  79306. return this._maxYaw;
  79307. },
  79308. set: function (value) {
  79309. this._maxYaw = value;
  79310. this._maxYawSin = Math.sin(value);
  79311. this._maxYawCos = Math.cos(value);
  79312. if (this._minYaw != null) {
  79313. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79314. this._yawRange = this._maxYaw - this._minYaw;
  79315. }
  79316. },
  79317. enumerable: true,
  79318. configurable: true
  79319. });
  79320. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79321. /**
  79322. * Gets or sets the minimum pitch angle that the bone can look to
  79323. */
  79324. get: function () {
  79325. return this._minPitch;
  79326. },
  79327. set: function (value) {
  79328. this._minPitch = value;
  79329. this._minPitchTan = Math.tan(value);
  79330. },
  79331. enumerable: true,
  79332. configurable: true
  79333. });
  79334. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79335. /**
  79336. * Gets or sets the maximum pitch angle that the bone can look to
  79337. */
  79338. get: function () {
  79339. return this._maxPitch;
  79340. },
  79341. set: function (value) {
  79342. this._maxPitch = value;
  79343. this._maxPitchTan = Math.tan(value);
  79344. },
  79345. enumerable: true,
  79346. configurable: true
  79347. });
  79348. /**
  79349. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79350. */
  79351. BoneLookController.prototype.update = function () {
  79352. //skip the first frame when slerping so that the mesh rotation is correct
  79353. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79354. this._firstFrameSkipped = true;
  79355. return;
  79356. }
  79357. var bone = this.bone;
  79358. var bonePos = BoneLookController._tmpVecs[0];
  79359. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79360. var target = this.target;
  79361. var _tmpMat1 = BoneLookController._tmpMats[0];
  79362. var _tmpMat2 = BoneLookController._tmpMats[1];
  79363. var mesh = this.mesh;
  79364. var parentBone = bone.getParent();
  79365. var upAxis = BoneLookController._tmpVecs[1];
  79366. upAxis.copyFrom(this.upAxis);
  79367. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79368. if (this._transformYawPitch) {
  79369. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79370. }
  79371. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79372. }
  79373. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79374. mesh.getDirectionToRef(upAxis, upAxis);
  79375. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79376. upAxis.normalize();
  79377. }
  79378. }
  79379. var checkYaw = false;
  79380. var checkPitch = false;
  79381. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79382. checkYaw = true;
  79383. }
  79384. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79385. checkPitch = true;
  79386. }
  79387. if (checkYaw || checkPitch) {
  79388. var spaceMat = BoneLookController._tmpMats[2];
  79389. var spaceMatInv = BoneLookController._tmpMats[3];
  79390. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79391. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79392. }
  79393. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79394. spaceMat.copyFrom(mesh.getWorldMatrix());
  79395. }
  79396. else {
  79397. var forwardAxis = BoneLookController._tmpVecs[2];
  79398. forwardAxis.copyFrom(this._fowardAxis);
  79399. if (this._transformYawPitch) {
  79400. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79401. }
  79402. if (parentBone) {
  79403. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79404. }
  79405. else {
  79406. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79407. }
  79408. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79409. rightAxis.normalize();
  79410. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79411. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79412. }
  79413. spaceMat.invertToRef(spaceMatInv);
  79414. var xzlen = null;
  79415. if (checkPitch) {
  79416. var localTarget = BoneLookController._tmpVecs[3];
  79417. target.subtractToRef(bonePos, localTarget);
  79418. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79419. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79420. var pitch = Math.atan2(localTarget.y, xzlen);
  79421. var newPitch = pitch;
  79422. if (pitch > this._maxPitch) {
  79423. localTarget.y = this._maxPitchTan * xzlen;
  79424. newPitch = this._maxPitch;
  79425. }
  79426. else if (pitch < this._minPitch) {
  79427. localTarget.y = this._minPitchTan * xzlen;
  79428. newPitch = this._minPitch;
  79429. }
  79430. if (pitch != newPitch) {
  79431. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79432. localTarget.addInPlace(bonePos);
  79433. target = localTarget;
  79434. }
  79435. }
  79436. if (checkYaw) {
  79437. var localTarget = BoneLookController._tmpVecs[4];
  79438. target.subtractToRef(bonePos, localTarget);
  79439. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79440. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79441. var newYaw = yaw;
  79442. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79443. if (xzlen == null) {
  79444. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79445. }
  79446. if (this._yawRange > Math.PI) {
  79447. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79448. localTarget.z = this._maxYawCos * xzlen;
  79449. localTarget.x = this._maxYawSin * xzlen;
  79450. newYaw = this._maxYaw;
  79451. }
  79452. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79453. localTarget.z = this._minYawCos * xzlen;
  79454. localTarget.x = this._minYawSin * xzlen;
  79455. newYaw = this._minYaw;
  79456. }
  79457. }
  79458. else {
  79459. if (yaw > this._maxYaw) {
  79460. localTarget.z = this._maxYawCos * xzlen;
  79461. localTarget.x = this._maxYawSin * xzlen;
  79462. newYaw = this._maxYaw;
  79463. }
  79464. else if (yaw < this._minYaw) {
  79465. localTarget.z = this._minYawCos * xzlen;
  79466. localTarget.x = this._minYawSin * xzlen;
  79467. newYaw = this._minYaw;
  79468. }
  79469. }
  79470. }
  79471. if (this._slerping && this._yawRange > Math.PI) {
  79472. //are we going to be crossing into the min/max region?
  79473. var boneFwd = BoneLookController._tmpVecs[8];
  79474. boneFwd.copyFrom(BABYLON.Axis.Z);
  79475. if (this._transformYawPitch) {
  79476. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79477. }
  79478. var boneRotMat = BoneLookController._tmpMats[4];
  79479. this._boneQuat.toRotationMatrix(boneRotMat);
  79480. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79481. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79482. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79483. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79484. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79485. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79486. if (angBtwTar > angBtwMidYaw) {
  79487. if (xzlen == null) {
  79488. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79489. }
  79490. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79491. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79492. if (angBtwMin < angBtwMax) {
  79493. newYaw = boneYaw + Math.PI * .75;
  79494. localTarget.z = Math.cos(newYaw) * xzlen;
  79495. localTarget.x = Math.sin(newYaw) * xzlen;
  79496. }
  79497. else {
  79498. newYaw = boneYaw - Math.PI * .75;
  79499. localTarget.z = Math.cos(newYaw) * xzlen;
  79500. localTarget.x = Math.sin(newYaw) * xzlen;
  79501. }
  79502. }
  79503. }
  79504. if (yaw != newYaw) {
  79505. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79506. localTarget.addInPlace(bonePos);
  79507. target = localTarget;
  79508. }
  79509. }
  79510. }
  79511. var zaxis = BoneLookController._tmpVecs[5];
  79512. var xaxis = BoneLookController._tmpVecs[6];
  79513. var yaxis = BoneLookController._tmpVecs[7];
  79514. var _tmpQuat = BoneLookController._tmpQuat;
  79515. target.subtractToRef(bonePos, zaxis);
  79516. zaxis.normalize();
  79517. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79518. xaxis.normalize();
  79519. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79520. yaxis.normalize();
  79521. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79522. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79523. return;
  79524. }
  79525. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79526. return;
  79527. }
  79528. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79529. return;
  79530. }
  79531. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79532. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79533. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79534. }
  79535. if (this.slerpAmount < 1) {
  79536. if (!this._slerping) {
  79537. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79538. }
  79539. if (this._transformYawPitch) {
  79540. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79541. }
  79542. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79543. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79544. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79545. this._slerping = true;
  79546. }
  79547. else {
  79548. if (this._transformYawPitch) {
  79549. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79550. }
  79551. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79552. this._slerping = false;
  79553. }
  79554. };
  79555. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79556. var angDiff = ang2 - ang1;
  79557. angDiff %= Math.PI * 2;
  79558. if (angDiff > Math.PI) {
  79559. angDiff -= Math.PI * 2;
  79560. }
  79561. else if (angDiff < -Math.PI) {
  79562. angDiff += Math.PI * 2;
  79563. }
  79564. return angDiff;
  79565. };
  79566. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79567. ang1 %= (2 * Math.PI);
  79568. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79569. ang2 %= (2 * Math.PI);
  79570. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79571. var ab = 0;
  79572. if (ang1 < ang2) {
  79573. ab = ang2 - ang1;
  79574. }
  79575. else {
  79576. ab = ang1 - ang2;
  79577. }
  79578. if (ab > Math.PI) {
  79579. ab = Math.PI * 2 - ab;
  79580. }
  79581. return ab;
  79582. };
  79583. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79584. ang %= (2 * Math.PI);
  79585. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79586. ang1 %= (2 * Math.PI);
  79587. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79588. ang2 %= (2 * Math.PI);
  79589. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79590. if (ang1 < ang2) {
  79591. if (ang > ang1 && ang < ang2) {
  79592. return true;
  79593. }
  79594. }
  79595. else {
  79596. if (ang > ang2 && ang < ang1) {
  79597. return true;
  79598. }
  79599. }
  79600. return false;
  79601. };
  79602. 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()];
  79603. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79604. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79605. return BoneLookController;
  79606. }());
  79607. BABYLON.BoneLookController = BoneLookController;
  79608. })(BABYLON || (BABYLON = {}));
  79609. //# sourceMappingURL=babylon.boneLookController.js.map
  79610. var BABYLON;
  79611. (function (BABYLON) {
  79612. /**
  79613. * Class used to handle skinning animations
  79614. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79615. */
  79616. var Skeleton = /** @class */ (function () {
  79617. /**
  79618. * Creates a new skeleton
  79619. * @param name defines the skeleton name
  79620. * @param id defines the skeleton Id
  79621. * @param scene defines the hosting scene
  79622. */
  79623. function Skeleton(
  79624. /** defines the skeleton name */
  79625. name,
  79626. /** defines the skeleton Id */
  79627. id, scene) {
  79628. this.name = name;
  79629. this.id = id;
  79630. /**
  79631. * Gets the list of child bones
  79632. */
  79633. this.bones = new Array();
  79634. /**
  79635. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79636. */
  79637. this.needInitialSkinMatrix = false;
  79638. this._isDirty = true;
  79639. this._meshesWithPoseMatrix = new Array();
  79640. this._identity = BABYLON.Matrix.Identity();
  79641. this._ranges = {};
  79642. this._lastAbsoluteTransformsUpdateId = -1;
  79643. /**
  79644. * Specifies if the skeleton should be serialized
  79645. */
  79646. this.doNotSerialize = false;
  79647. this._animationPropertiesOverride = null;
  79648. // Events
  79649. /**
  79650. * An observable triggered before computing the skeleton's matrices
  79651. */
  79652. this.onBeforeComputeObservable = new BABYLON.Observable();
  79653. this.bones = [];
  79654. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79655. scene.skeletons.push(this);
  79656. //make sure it will recalculate the matrix next time prepare is called.
  79657. this._isDirty = true;
  79658. }
  79659. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79660. /**
  79661. * Gets or sets the animation properties override
  79662. */
  79663. get: function () {
  79664. if (!this._animationPropertiesOverride) {
  79665. return this._scene.animationPropertiesOverride;
  79666. }
  79667. return this._animationPropertiesOverride;
  79668. },
  79669. set: function (value) {
  79670. this._animationPropertiesOverride = value;
  79671. },
  79672. enumerable: true,
  79673. configurable: true
  79674. });
  79675. // Members
  79676. /**
  79677. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79678. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79679. * @returns a Float32Array containing matrices data
  79680. */
  79681. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79682. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79683. return mesh._bonesTransformMatrices;
  79684. }
  79685. if (!this._transformMatrices) {
  79686. this.prepare();
  79687. }
  79688. return this._transformMatrices;
  79689. };
  79690. /**
  79691. * Gets the current hosting scene
  79692. * @returns a scene object
  79693. */
  79694. Skeleton.prototype.getScene = function () {
  79695. return this._scene;
  79696. };
  79697. // Methods
  79698. /**
  79699. * Gets a string representing the current skeleton data
  79700. * @param fullDetails defines a boolean indicating if we want a verbose version
  79701. * @returns a string representing the current skeleton data
  79702. */
  79703. Skeleton.prototype.toString = function (fullDetails) {
  79704. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79705. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79706. if (fullDetails) {
  79707. ret += ", Ranges: {";
  79708. var first = true;
  79709. for (var name_1 in this._ranges) {
  79710. if (first) {
  79711. ret += ", ";
  79712. first = false;
  79713. }
  79714. ret += name_1;
  79715. }
  79716. ret += "}";
  79717. }
  79718. return ret;
  79719. };
  79720. /**
  79721. * Get bone's index searching by name
  79722. * @param name defines bone's name to search for
  79723. * @return the indice of the bone. Returns -1 if not found
  79724. */
  79725. Skeleton.prototype.getBoneIndexByName = function (name) {
  79726. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79727. if (this.bones[boneIndex].name === name) {
  79728. return boneIndex;
  79729. }
  79730. }
  79731. return -1;
  79732. };
  79733. /**
  79734. * Creater a new animation range
  79735. * @param name defines the name of the range
  79736. * @param from defines the start key
  79737. * @param to defines the end key
  79738. */
  79739. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79740. // check name not already in use
  79741. if (!this._ranges[name]) {
  79742. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79743. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79744. if (this.bones[i].animations[0]) {
  79745. this.bones[i].animations[0].createRange(name, from, to);
  79746. }
  79747. }
  79748. }
  79749. };
  79750. /**
  79751. * Delete a specific animation range
  79752. * @param name defines the name of the range
  79753. * @param deleteFrames defines if frames must be removed as well
  79754. */
  79755. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79756. if (deleteFrames === void 0) { deleteFrames = true; }
  79757. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79758. if (this.bones[i].animations[0]) {
  79759. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79760. }
  79761. }
  79762. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79763. };
  79764. /**
  79765. * Gets a specific animation range
  79766. * @param name defines the name of the range to look for
  79767. * @returns the requested animation range or null if not found
  79768. */
  79769. Skeleton.prototype.getAnimationRange = function (name) {
  79770. return this._ranges[name];
  79771. };
  79772. /**
  79773. * Gets the list of all animation ranges defined on this skeleton
  79774. * @returns an array
  79775. */
  79776. Skeleton.prototype.getAnimationRanges = function () {
  79777. var animationRanges = [];
  79778. var name;
  79779. var i = 0;
  79780. for (name in this._ranges) {
  79781. animationRanges[i] = this._ranges[name];
  79782. i++;
  79783. }
  79784. return animationRanges;
  79785. };
  79786. /**
  79787. * Copy animation range from a source skeleton.
  79788. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79789. * @param source defines the source skeleton
  79790. * @param name defines the name of the range to copy
  79791. * @param rescaleAsRequired defines if rescaling must be applied if required
  79792. * @returns true if operation was successful
  79793. */
  79794. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79795. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79796. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79797. return false;
  79798. }
  79799. var ret = true;
  79800. var frameOffset = this._getHighestAnimationFrame() + 1;
  79801. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79802. var boneDict = {};
  79803. var sourceBones = source.bones;
  79804. var nBones;
  79805. var i;
  79806. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79807. boneDict[sourceBones[i].name] = sourceBones[i];
  79808. }
  79809. if (this.bones.length !== sourceBones.length) {
  79810. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79811. ret = false;
  79812. }
  79813. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79814. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79815. var boneName = this.bones[i].name;
  79816. var sourceBone = boneDict[boneName];
  79817. if (sourceBone) {
  79818. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79819. }
  79820. else {
  79821. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79822. ret = false;
  79823. }
  79824. }
  79825. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79826. var range = source.getAnimationRange(name);
  79827. if (range) {
  79828. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79829. }
  79830. return ret;
  79831. };
  79832. /**
  79833. * Forces the skeleton to go to rest pose
  79834. */
  79835. Skeleton.prototype.returnToRest = function () {
  79836. for (var index = 0; index < this.bones.length; index++) {
  79837. this.bones[index].returnToRest();
  79838. }
  79839. };
  79840. Skeleton.prototype._getHighestAnimationFrame = function () {
  79841. var ret = 0;
  79842. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79843. if (this.bones[i].animations[0]) {
  79844. var highest = this.bones[i].animations[0].getHighestFrame();
  79845. if (ret < highest) {
  79846. ret = highest;
  79847. }
  79848. }
  79849. }
  79850. return ret;
  79851. };
  79852. /**
  79853. * Begin a specific animation range
  79854. * @param name defines the name of the range to start
  79855. * @param loop defines if looping must be turned on (false by default)
  79856. * @param speedRatio defines the speed ratio to apply (1 by default)
  79857. * @param onAnimationEnd defines a callback which will be called when animation will end
  79858. * @returns a new animatable
  79859. */
  79860. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79861. var range = this.getAnimationRange(name);
  79862. if (!range) {
  79863. return null;
  79864. }
  79865. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79866. };
  79867. /** @hidden */
  79868. Skeleton.prototype._markAsDirty = function () {
  79869. this._isDirty = true;
  79870. };
  79871. /** @hidden */
  79872. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79873. this._meshesWithPoseMatrix.push(mesh);
  79874. };
  79875. /** @hidden */
  79876. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79877. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79878. if (index > -1) {
  79879. this._meshesWithPoseMatrix.splice(index, 1);
  79880. }
  79881. };
  79882. /** @hidden */
  79883. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79884. this.onBeforeComputeObservable.notifyObservers(this);
  79885. for (var index = 0; index < this.bones.length; index++) {
  79886. var bone = this.bones[index];
  79887. var parentBone = bone.getParent();
  79888. if (parentBone) {
  79889. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79890. }
  79891. else {
  79892. if (initialSkinMatrix) {
  79893. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79894. }
  79895. else {
  79896. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79897. }
  79898. }
  79899. if (bone._index !== -1) {
  79900. var mappedIndex = bone._index === null ? index : bone._index;
  79901. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79902. }
  79903. }
  79904. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79905. };
  79906. /**
  79907. * Build all resources required to render a skeleton
  79908. */
  79909. Skeleton.prototype.prepare = function () {
  79910. if (!this._isDirty) {
  79911. return;
  79912. }
  79913. if (this.needInitialSkinMatrix) {
  79914. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79915. var mesh = this._meshesWithPoseMatrix[index];
  79916. var poseMatrix = mesh.getPoseMatrix();
  79917. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79918. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79919. }
  79920. if (this._synchronizedWithMesh !== mesh) {
  79921. this._synchronizedWithMesh = mesh;
  79922. // Prepare bones
  79923. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79924. var bone = this.bones[boneIndex];
  79925. if (!bone.getParent()) {
  79926. var matrix = bone.getBaseMatrix();
  79927. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79928. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79929. }
  79930. }
  79931. }
  79932. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79933. }
  79934. }
  79935. else {
  79936. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79937. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79938. }
  79939. this._computeTransformMatrices(this._transformMatrices, null);
  79940. }
  79941. this._isDirty = false;
  79942. this._scene._activeBones.addCount(this.bones.length, false);
  79943. };
  79944. /**
  79945. * Gets the list of animatables currently running for this skeleton
  79946. * @returns an array of animatables
  79947. */
  79948. Skeleton.prototype.getAnimatables = function () {
  79949. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79950. this._animatables = [];
  79951. for (var index = 0; index < this.bones.length; index++) {
  79952. this._animatables.push(this.bones[index]);
  79953. }
  79954. }
  79955. return this._animatables;
  79956. };
  79957. /**
  79958. * Clone the current skeleton
  79959. * @param name defines the name of the new skeleton
  79960. * @param id defines the id of the enw skeleton
  79961. * @returns the new skeleton
  79962. */
  79963. Skeleton.prototype.clone = function (name, id) {
  79964. var result = new Skeleton(name, id || name, this._scene);
  79965. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79966. for (var index = 0; index < this.bones.length; index++) {
  79967. var source = this.bones[index];
  79968. var parentBone = null;
  79969. var parent_1 = source.getParent();
  79970. if (parent_1) {
  79971. var parentIndex = this.bones.indexOf(parent_1);
  79972. parentBone = result.bones[parentIndex];
  79973. }
  79974. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79975. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79976. }
  79977. if (this._ranges) {
  79978. result._ranges = {};
  79979. for (var rangeName in this._ranges) {
  79980. var range = this._ranges[rangeName];
  79981. if (range) {
  79982. result._ranges[rangeName] = range.clone();
  79983. }
  79984. }
  79985. }
  79986. this._isDirty = true;
  79987. return result;
  79988. };
  79989. /**
  79990. * Enable animation blending for this skeleton
  79991. * @param blendingSpeed defines the blending speed to apply
  79992. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79993. */
  79994. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79995. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79996. this.bones.forEach(function (bone) {
  79997. bone.animations.forEach(function (animation) {
  79998. animation.enableBlending = true;
  79999. animation.blendingSpeed = blendingSpeed;
  80000. });
  80001. });
  80002. };
  80003. /**
  80004. * Releases all resources associated with the current skeleton
  80005. */
  80006. Skeleton.prototype.dispose = function () {
  80007. this._meshesWithPoseMatrix = [];
  80008. // Animations
  80009. this.getScene().stopAnimation(this);
  80010. // Remove from scene
  80011. this.getScene().removeSkeleton(this);
  80012. };
  80013. /**
  80014. * Serialize the skeleton in a JSON object
  80015. * @returns a JSON object
  80016. */
  80017. Skeleton.prototype.serialize = function () {
  80018. var serializationObject = {};
  80019. serializationObject.name = this.name;
  80020. serializationObject.id = this.id;
  80021. if (this.dimensionsAtRest) {
  80022. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80023. }
  80024. serializationObject.bones = [];
  80025. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80026. for (var index = 0; index < this.bones.length; index++) {
  80027. var bone = this.bones[index];
  80028. var parent_2 = bone.getParent();
  80029. var serializedBone = {
  80030. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80031. name: bone.name,
  80032. matrix: bone.getBaseMatrix().toArray(),
  80033. rest: bone.getRestPose().toArray()
  80034. };
  80035. serializationObject.bones.push(serializedBone);
  80036. if (bone.length) {
  80037. serializedBone.length = bone.length;
  80038. }
  80039. if (bone.metadata) {
  80040. serializedBone.metadata = bone.metadata;
  80041. }
  80042. if (bone.animations && bone.animations.length > 0) {
  80043. serializedBone.animation = bone.animations[0].serialize();
  80044. }
  80045. serializationObject.ranges = [];
  80046. for (var name in this._ranges) {
  80047. var source = this._ranges[name];
  80048. if (!source) {
  80049. continue;
  80050. }
  80051. var range = {};
  80052. range.name = name;
  80053. range.from = source.from;
  80054. range.to = source.to;
  80055. serializationObject.ranges.push(range);
  80056. }
  80057. }
  80058. return serializationObject;
  80059. };
  80060. /**
  80061. * Creates a new skeleton from serialized data
  80062. * @param parsedSkeleton defines the serialized data
  80063. * @param scene defines the hosting scene
  80064. * @returns a new skeleton
  80065. */
  80066. Skeleton.Parse = function (parsedSkeleton, scene) {
  80067. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80068. if (parsedSkeleton.dimensionsAtRest) {
  80069. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80070. }
  80071. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80072. var index;
  80073. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80074. var parsedBone = parsedSkeleton.bones[index];
  80075. var parentBone = null;
  80076. if (parsedBone.parentBoneIndex > -1) {
  80077. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80078. }
  80079. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80080. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80081. if (parsedBone.length) {
  80082. bone.length = parsedBone.length;
  80083. }
  80084. if (parsedBone.metadata) {
  80085. bone.metadata = parsedBone.metadata;
  80086. }
  80087. if (parsedBone.animation) {
  80088. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80089. }
  80090. }
  80091. // placed after bones, so createAnimationRange can cascade down
  80092. if (parsedSkeleton.ranges) {
  80093. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80094. var data = parsedSkeleton.ranges[index];
  80095. skeleton.createAnimationRange(data.name, data.from, data.to);
  80096. }
  80097. }
  80098. return skeleton;
  80099. };
  80100. /**
  80101. * Compute all node absolute transforms
  80102. * @param forceUpdate defines if computation must be done even if cache is up to date
  80103. */
  80104. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80105. if (forceUpdate === void 0) { forceUpdate = false; }
  80106. var renderId = this._scene.getRenderId();
  80107. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80108. this.bones[0].computeAbsoluteTransforms();
  80109. this._lastAbsoluteTransformsUpdateId = renderId;
  80110. }
  80111. };
  80112. /**
  80113. * Gets the root pose matrix
  80114. * @returns a matrix
  80115. */
  80116. Skeleton.prototype.getPoseMatrix = function () {
  80117. var poseMatrix = null;
  80118. if (this._meshesWithPoseMatrix.length > 0) {
  80119. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80120. }
  80121. return poseMatrix;
  80122. };
  80123. /**
  80124. * Sorts bones per internal index
  80125. */
  80126. Skeleton.prototype.sortBones = function () {
  80127. var bones = new Array();
  80128. var visited = new Array(this.bones.length);
  80129. for (var index = 0; index < this.bones.length; index++) {
  80130. this._sortBones(index, bones, visited);
  80131. }
  80132. this.bones = bones;
  80133. };
  80134. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80135. if (visited[index]) {
  80136. return;
  80137. }
  80138. visited[index] = true;
  80139. var bone = this.bones[index];
  80140. if (bone._index === undefined) {
  80141. bone._index = index;
  80142. }
  80143. var parentBone = bone.getParent();
  80144. if (parentBone) {
  80145. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80146. }
  80147. bones.push(bone);
  80148. };
  80149. return Skeleton;
  80150. }());
  80151. BABYLON.Skeleton = Skeleton;
  80152. })(BABYLON || (BABYLON = {}));
  80153. //# sourceMappingURL=babylon.skeleton.js.map
  80154. var BABYLON;
  80155. (function (BABYLON) {
  80156. var SphericalPolynomial = /** @class */ (function () {
  80157. function SphericalPolynomial() {
  80158. this.x = BABYLON.Vector3.Zero();
  80159. this.y = BABYLON.Vector3.Zero();
  80160. this.z = BABYLON.Vector3.Zero();
  80161. this.xx = BABYLON.Vector3.Zero();
  80162. this.yy = BABYLON.Vector3.Zero();
  80163. this.zz = BABYLON.Vector3.Zero();
  80164. this.xy = BABYLON.Vector3.Zero();
  80165. this.yz = BABYLON.Vector3.Zero();
  80166. this.zx = BABYLON.Vector3.Zero();
  80167. }
  80168. SphericalPolynomial.prototype.addAmbient = function (color) {
  80169. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80170. this.xx = this.xx.add(colorVector);
  80171. this.yy = this.yy.add(colorVector);
  80172. this.zz = this.zz.add(colorVector);
  80173. };
  80174. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80175. var result = new SphericalPolynomial();
  80176. result.x = harmonics.L11.scale(1.02333);
  80177. result.y = harmonics.L1_1.scale(1.02333);
  80178. result.z = harmonics.L10.scale(1.02333);
  80179. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80180. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80181. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80182. result.yz = harmonics.L2_1.scale(0.858086);
  80183. result.zx = harmonics.L21.scale(0.858086);
  80184. result.xy = harmonics.L2_2.scale(0.858086);
  80185. result.scale(1.0 / Math.PI);
  80186. return result;
  80187. };
  80188. SphericalPolynomial.prototype.scale = function (scale) {
  80189. this.x = this.x.scale(scale);
  80190. this.y = this.y.scale(scale);
  80191. this.z = this.z.scale(scale);
  80192. this.xx = this.xx.scale(scale);
  80193. this.yy = this.yy.scale(scale);
  80194. this.zz = this.zz.scale(scale);
  80195. this.yz = this.yz.scale(scale);
  80196. this.zx = this.zx.scale(scale);
  80197. this.xy = this.xy.scale(scale);
  80198. };
  80199. return SphericalPolynomial;
  80200. }());
  80201. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80202. var SphericalHarmonics = /** @class */ (function () {
  80203. function SphericalHarmonics() {
  80204. this.L00 = BABYLON.Vector3.Zero();
  80205. this.L1_1 = BABYLON.Vector3.Zero();
  80206. this.L10 = BABYLON.Vector3.Zero();
  80207. this.L11 = BABYLON.Vector3.Zero();
  80208. this.L2_2 = BABYLON.Vector3.Zero();
  80209. this.L2_1 = BABYLON.Vector3.Zero();
  80210. this.L20 = BABYLON.Vector3.Zero();
  80211. this.L21 = BABYLON.Vector3.Zero();
  80212. this.L22 = BABYLON.Vector3.Zero();
  80213. }
  80214. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80215. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80216. var c = colorVector.scale(deltaSolidAngle);
  80217. this.L00 = this.L00.add(c.scale(0.282095));
  80218. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80219. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80220. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80221. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80222. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80223. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80224. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80225. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80226. };
  80227. SphericalHarmonics.prototype.scale = function (scale) {
  80228. this.L00 = this.L00.scale(scale);
  80229. this.L1_1 = this.L1_1.scale(scale);
  80230. this.L10 = this.L10.scale(scale);
  80231. this.L11 = this.L11.scale(scale);
  80232. this.L2_2 = this.L2_2.scale(scale);
  80233. this.L2_1 = this.L2_1.scale(scale);
  80234. this.L20 = this.L20.scale(scale);
  80235. this.L21 = this.L21.scale(scale);
  80236. this.L22 = this.L22.scale(scale);
  80237. };
  80238. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80239. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80240. //
  80241. // E_lm = A_l * L_lm
  80242. //
  80243. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80244. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80245. // the scaling factors are given in equation 9.
  80246. // Constant (Band 0)
  80247. this.L00 = this.L00.scale(3.141593);
  80248. // Linear (Band 1)
  80249. this.L1_1 = this.L1_1.scale(2.094395);
  80250. this.L10 = this.L10.scale(2.094395);
  80251. this.L11 = this.L11.scale(2.094395);
  80252. // Quadratic (Band 2)
  80253. this.L2_2 = this.L2_2.scale(0.785398);
  80254. this.L2_1 = this.L2_1.scale(0.785398);
  80255. this.L20 = this.L20.scale(0.785398);
  80256. this.L21 = this.L21.scale(0.785398);
  80257. this.L22 = this.L22.scale(0.785398);
  80258. };
  80259. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80260. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80261. // L = (1/pi) * E * rho
  80262. //
  80263. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80264. this.scale(1.0 / Math.PI);
  80265. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80266. // (The pixel shader must apply albedo after texture fetches, etc).
  80267. };
  80268. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80269. var result = new SphericalHarmonics();
  80270. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80271. result.L1_1 = polynomial.y.scale(0.977204);
  80272. result.L10 = polynomial.z.scale(0.977204);
  80273. result.L11 = polynomial.x.scale(0.977204);
  80274. result.L2_2 = polynomial.xy.scale(1.16538);
  80275. result.L2_1 = polynomial.yz.scale(1.16538);
  80276. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80277. result.L21 = polynomial.zx.scale(1.16538);
  80278. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80279. result.scale(Math.PI);
  80280. return result;
  80281. };
  80282. return SphericalHarmonics;
  80283. }());
  80284. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80285. })(BABYLON || (BABYLON = {}));
  80286. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80287. var BABYLON;
  80288. (function (BABYLON) {
  80289. var FileFaceOrientation = /** @class */ (function () {
  80290. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80291. this.name = name;
  80292. this.worldAxisForNormal = worldAxisForNormal;
  80293. this.worldAxisForFileX = worldAxisForFileX;
  80294. this.worldAxisForFileY = worldAxisForFileY;
  80295. }
  80296. return FileFaceOrientation;
  80297. }());
  80298. ;
  80299. /**
  80300. * Helper class dealing with the extraction of spherical polynomial dataArray
  80301. * from a cube map.
  80302. */
  80303. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80304. function CubeMapToSphericalPolynomialTools() {
  80305. }
  80306. /**
  80307. * Converts a texture to the according Spherical Polynomial data.
  80308. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80309. *
  80310. * @param texture The texture to extract the information from.
  80311. * @return The Spherical Polynomial data.
  80312. */
  80313. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80314. if (!texture.isCube) {
  80315. // Only supports cube Textures currently.
  80316. return null;
  80317. }
  80318. var size = texture.getSize().width;
  80319. var right = texture.readPixels(0);
  80320. var left = texture.readPixels(1);
  80321. var up;
  80322. var down;
  80323. if (texture.isRenderTarget) {
  80324. up = texture.readPixels(3);
  80325. down = texture.readPixels(2);
  80326. }
  80327. else {
  80328. up = texture.readPixels(2);
  80329. down = texture.readPixels(3);
  80330. }
  80331. var front = texture.readPixels(4);
  80332. var back = texture.readPixels(5);
  80333. var gammaSpace = texture.gammaSpace;
  80334. // Always read as RGBA.
  80335. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80336. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80337. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80338. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80339. }
  80340. var cubeInfo = {
  80341. size: size,
  80342. right: right,
  80343. left: left,
  80344. up: up,
  80345. down: down,
  80346. front: front,
  80347. back: back,
  80348. format: format,
  80349. type: type,
  80350. gammaSpace: gammaSpace,
  80351. };
  80352. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80353. };
  80354. /**
  80355. * Converts a cubemap to the according Spherical Polynomial data.
  80356. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80357. *
  80358. * @param cubeInfo The Cube map to extract the information from.
  80359. * @return The Spherical Polynomial data.
  80360. */
  80361. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80362. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80363. var totalSolidAngle = 0.0;
  80364. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80365. var du = 2.0 / cubeInfo.size;
  80366. var dv = du;
  80367. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80368. var minUV = du * 0.5 - 1.0;
  80369. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80370. var fileFace = this.FileFaces[faceIndex];
  80371. var dataArray = cubeInfo[fileFace.name];
  80372. var v = minUV;
  80373. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80374. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80375. // Because SP is still linear, so summation is fine in that basis.
  80376. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80377. for (var y = 0; y < cubeInfo.size; y++) {
  80378. var u = minUV;
  80379. for (var x = 0; x < cubeInfo.size; x++) {
  80380. // World direction (not normalised)
  80381. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80382. worldDirection.normalize();
  80383. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80384. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80385. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80386. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80387. // Handle Integer types.
  80388. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80389. r /= 255;
  80390. g /= 255;
  80391. b /= 255;
  80392. }
  80393. // Handle Gamma space textures.
  80394. if (cubeInfo.gammaSpace) {
  80395. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80396. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80397. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80398. }
  80399. var color = new BABYLON.Color3(r, g, b);
  80400. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80401. totalSolidAngle += deltaSolidAngle;
  80402. u += du;
  80403. }
  80404. v += dv;
  80405. }
  80406. }
  80407. // Solid angle for entire sphere is 4*pi
  80408. var sphereSolidAngle = 4.0 * Math.PI;
  80409. // Adjust the solid angle to allow for how many faces we processed.
  80410. var facesProcessed = 6.0;
  80411. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80412. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80413. // This is needed because the numerical integration over the cube uses a
  80414. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80415. // and also to compensate for accumulative error due to float precision in the summation.
  80416. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80417. sphericalHarmonics.scale(correctionFactor);
  80418. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80419. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80420. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80421. };
  80422. CubeMapToSphericalPolynomialTools.FileFaces = [
  80423. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80424. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80425. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80426. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80427. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80428. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80429. ];
  80430. return CubeMapToSphericalPolynomialTools;
  80431. }());
  80432. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80433. })(BABYLON || (BABYLON = {}));
  80434. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80435. var BABYLON;
  80436. (function (BABYLON) {
  80437. /**
  80438. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80439. */
  80440. var PanoramaToCubeMapTools = /** @class */ (function () {
  80441. function PanoramaToCubeMapTools() {
  80442. }
  80443. /**
  80444. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80445. *
  80446. * @param float32Array The source data.
  80447. * @param inputWidth The width of the input panorama.
  80448. * @param inputhHeight The height of the input panorama.
  80449. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80450. * @return The cubemap data
  80451. */
  80452. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80453. if (!float32Array) {
  80454. throw "ConvertPanoramaToCubemap: input cannot be null";
  80455. }
  80456. if (float32Array.length != inputWidth * inputHeight * 3) {
  80457. throw "ConvertPanoramaToCubemap: input size is wrong";
  80458. }
  80459. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80460. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80461. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80462. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80463. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80464. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80465. return {
  80466. front: textureFront,
  80467. back: textureBack,
  80468. left: textureLeft,
  80469. right: textureRight,
  80470. up: textureUp,
  80471. down: textureDown,
  80472. size: size,
  80473. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80474. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80475. gammaSpace: false,
  80476. };
  80477. };
  80478. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80479. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80480. var textureArray = new Float32Array(buffer);
  80481. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80482. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80483. var dy = 1 / texSize;
  80484. var fy = 0;
  80485. for (var y = 0; y < texSize; y++) {
  80486. var xv1 = faceData[0];
  80487. var xv2 = faceData[2];
  80488. for (var x = 0; x < texSize; x++) {
  80489. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80490. v.normalize();
  80491. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80492. // 3 channels per pixels
  80493. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80494. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80495. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80496. xv1 = xv1.add(rotDX1);
  80497. xv2 = xv2.add(rotDX2);
  80498. }
  80499. fy += dy;
  80500. }
  80501. return textureArray;
  80502. };
  80503. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80504. var theta = Math.atan2(vDir.z, vDir.x);
  80505. var phi = Math.acos(vDir.y);
  80506. while (theta < -Math.PI)
  80507. theta += 2 * Math.PI;
  80508. while (theta > Math.PI)
  80509. theta -= 2 * Math.PI;
  80510. var dx = theta / Math.PI;
  80511. var dy = phi / Math.PI;
  80512. // recenter.
  80513. dx = dx * 0.5 + 0.5;
  80514. var px = Math.round(dx * inputWidth);
  80515. if (px < 0)
  80516. px = 0;
  80517. else if (px >= inputWidth)
  80518. px = inputWidth - 1;
  80519. var py = Math.round(dy * inputHeight);
  80520. if (py < 0)
  80521. py = 0;
  80522. else if (py >= inputHeight)
  80523. py = inputHeight - 1;
  80524. var inputY = (inputHeight - py - 1);
  80525. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80526. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80527. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80528. return {
  80529. r: r,
  80530. g: g,
  80531. b: b
  80532. };
  80533. };
  80534. PanoramaToCubeMapTools.FACE_FRONT = [
  80535. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80536. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80537. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80538. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80539. ];
  80540. PanoramaToCubeMapTools.FACE_BACK = [
  80541. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80542. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80543. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80544. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80545. ];
  80546. PanoramaToCubeMapTools.FACE_RIGHT = [
  80547. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80548. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80549. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80550. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80551. ];
  80552. PanoramaToCubeMapTools.FACE_LEFT = [
  80553. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80554. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80555. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80556. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80557. ];
  80558. PanoramaToCubeMapTools.FACE_DOWN = [
  80559. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80560. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80561. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80562. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80563. ];
  80564. PanoramaToCubeMapTools.FACE_UP = [
  80565. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80566. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80567. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80568. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80569. ];
  80570. return PanoramaToCubeMapTools;
  80571. }());
  80572. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80573. })(BABYLON || (BABYLON = {}));
  80574. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80575. var BABYLON;
  80576. (function (BABYLON) {
  80577. ;
  80578. /**
  80579. * This groups tools to convert HDR texture to native colors array.
  80580. */
  80581. var HDRTools = /** @class */ (function () {
  80582. function HDRTools() {
  80583. }
  80584. HDRTools.Ldexp = function (mantissa, exponent) {
  80585. if (exponent > 1023) {
  80586. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80587. }
  80588. if (exponent < -1074) {
  80589. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80590. }
  80591. return mantissa * Math.pow(2, exponent);
  80592. };
  80593. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80594. if (exponent > 0) { /*nonzero pixel*/
  80595. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80596. float32array[index + 0] = red * exponent;
  80597. float32array[index + 1] = green * exponent;
  80598. float32array[index + 2] = blue * exponent;
  80599. }
  80600. else {
  80601. float32array[index + 0] = 0;
  80602. float32array[index + 1] = 0;
  80603. float32array[index + 2] = 0;
  80604. }
  80605. };
  80606. HDRTools.readStringLine = function (uint8array, startIndex) {
  80607. var line = "";
  80608. var character = "";
  80609. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80610. character = String.fromCharCode(uint8array[i]);
  80611. if (character == "\n") {
  80612. break;
  80613. }
  80614. line += character;
  80615. }
  80616. return line;
  80617. };
  80618. /**
  80619. * Reads header information from an RGBE texture stored in a native array.
  80620. * More information on this format are available here:
  80621. * https://en.wikipedia.org/wiki/RGBE_image_format
  80622. *
  80623. * @param uint8array The binary file stored in native array.
  80624. * @return The header information.
  80625. */
  80626. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80627. var height = 0;
  80628. var width = 0;
  80629. var line = this.readStringLine(uint8array, 0);
  80630. if (line[0] != '#' || line[1] != '?') {
  80631. throw "Bad HDR Format.";
  80632. }
  80633. var endOfHeader = false;
  80634. var findFormat = false;
  80635. var lineIndex = 0;
  80636. do {
  80637. lineIndex += (line.length + 1);
  80638. line = this.readStringLine(uint8array, lineIndex);
  80639. if (line == "FORMAT=32-bit_rle_rgbe") {
  80640. findFormat = true;
  80641. }
  80642. else if (line.length == 0) {
  80643. endOfHeader = true;
  80644. }
  80645. } while (!endOfHeader);
  80646. if (!findFormat) {
  80647. throw "HDR Bad header format, unsupported FORMAT";
  80648. }
  80649. lineIndex += (line.length + 1);
  80650. line = this.readStringLine(uint8array, lineIndex);
  80651. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80652. var match = sizeRegexp.exec(line);
  80653. // TODO. Support +Y and -X if needed.
  80654. if (!match || match.length < 3) {
  80655. throw "HDR Bad header format, no size";
  80656. }
  80657. width = parseInt(match[2]);
  80658. height = parseInt(match[1]);
  80659. if (width < 8 || width > 0x7fff) {
  80660. throw "HDR Bad header format, unsupported size";
  80661. }
  80662. lineIndex += (line.length + 1);
  80663. return {
  80664. height: height,
  80665. width: width,
  80666. dataPosition: lineIndex
  80667. };
  80668. };
  80669. /**
  80670. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80671. * This RGBE texture needs to store the information as a panorama.
  80672. *
  80673. * More information on this format are available here:
  80674. * https://en.wikipedia.org/wiki/RGBE_image_format
  80675. *
  80676. * @param buffer The binary file stored in an array buffer.
  80677. * @param size The expected size of the extracted cubemap.
  80678. * @return The Cube Map information.
  80679. */
  80680. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80681. var uint8array = new Uint8Array(buffer);
  80682. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80683. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80684. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80685. return cubeMapData;
  80686. };
  80687. /**
  80688. * Returns the pixels data extracted from an RGBE texture.
  80689. * This pixels will be stored left to right up to down in the R G B order in one array.
  80690. *
  80691. * More information on this format are available here:
  80692. * https://en.wikipedia.org/wiki/RGBE_image_format
  80693. *
  80694. * @param uint8array The binary file stored in an array buffer.
  80695. * @param hdrInfo The header information of the file.
  80696. * @return The pixels data in RGB right to left up to down order.
  80697. */
  80698. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80699. // Keep for multi format supports.
  80700. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80701. };
  80702. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80703. var num_scanlines = hdrInfo.height;
  80704. var scanline_width = hdrInfo.width;
  80705. var a, b, c, d, count;
  80706. var dataIndex = hdrInfo.dataPosition;
  80707. var index = 0, endIndex = 0, i = 0;
  80708. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80709. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80710. // 3 channels of 4 bytes per pixel in float.
  80711. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80712. var resultArray = new Float32Array(resultBuffer);
  80713. // read in each successive scanline
  80714. while (num_scanlines > 0) {
  80715. a = uint8array[dataIndex++];
  80716. b = uint8array[dataIndex++];
  80717. c = uint8array[dataIndex++];
  80718. d = uint8array[dataIndex++];
  80719. if (a != 2 || b != 2 || (c & 0x80)) {
  80720. // this file is not run length encoded
  80721. throw "HDR Bad header format, not RLE";
  80722. }
  80723. if (((c << 8) | d) != scanline_width) {
  80724. throw "HDR Bad header format, wrong scan line width";
  80725. }
  80726. index = 0;
  80727. // read each of the four channels for the scanline into the buffer
  80728. for (i = 0; i < 4; i++) {
  80729. endIndex = (i + 1) * scanline_width;
  80730. while (index < endIndex) {
  80731. a = uint8array[dataIndex++];
  80732. b = uint8array[dataIndex++];
  80733. if (a > 128) {
  80734. // a run of the same value
  80735. count = a - 128;
  80736. if ((count == 0) || (count > endIndex - index)) {
  80737. throw "HDR Bad Format, bad scanline data (run)";
  80738. }
  80739. while (count-- > 0) {
  80740. scanLineArray[index++] = b;
  80741. }
  80742. }
  80743. else {
  80744. // a non-run
  80745. count = a;
  80746. if ((count == 0) || (count > endIndex - index)) {
  80747. throw "HDR Bad Format, bad scanline data (non-run)";
  80748. }
  80749. scanLineArray[index++] = b;
  80750. if (--count > 0) {
  80751. for (var j = 0; j < count; j++) {
  80752. scanLineArray[index++] = uint8array[dataIndex++];
  80753. }
  80754. }
  80755. }
  80756. }
  80757. }
  80758. // now convert data from buffer into floats
  80759. for (i = 0; i < scanline_width; i++) {
  80760. a = scanLineArray[i];
  80761. b = scanLineArray[i + scanline_width];
  80762. c = scanLineArray[i + 2 * scanline_width];
  80763. d = scanLineArray[i + 3 * scanline_width];
  80764. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80765. }
  80766. num_scanlines--;
  80767. }
  80768. return resultArray;
  80769. };
  80770. return HDRTools;
  80771. }());
  80772. BABYLON.HDRTools = HDRTools;
  80773. })(BABYLON || (BABYLON = {}));
  80774. //# sourceMappingURL=babylon.hdr.js.map
  80775. var BABYLON;
  80776. (function (BABYLON) {
  80777. /**
  80778. * This represents a texture coming from an HDR input.
  80779. *
  80780. * The only supported format is currently panorama picture stored in RGBE format.
  80781. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80782. */
  80783. var HDRCubeTexture = /** @class */ (function (_super) {
  80784. __extends(HDRCubeTexture, _super);
  80785. /**
  80786. * Instantiates an HDRTexture from the following parameters.
  80787. *
  80788. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80789. * @param scene The scene the texture will be used in
  80790. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80791. * @param noMipmap Forces to not generate the mipmap if true
  80792. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80793. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  80794. * @param reserved Reserved flag for internal use.
  80795. */
  80796. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80797. if (noMipmap === void 0) { noMipmap = false; }
  80798. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80799. if (gammaSpace === void 0) { gammaSpace = false; }
  80800. if (reserved === void 0) { reserved = false; }
  80801. if (onLoad === void 0) { onLoad = null; }
  80802. if (onError === void 0) { onError = null; }
  80803. var _this = _super.call(this, scene) || this;
  80804. _this._generateHarmonics = true;
  80805. _this._onLoad = null;
  80806. _this._onError = null;
  80807. /**
  80808. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80809. */
  80810. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80811. _this._isBlocking = true;
  80812. _this._rotationY = 0;
  80813. /**
  80814. * Gets or sets the center of the bounding box associated with the cube texture
  80815. * It must define where the camera used to render the texture was set
  80816. */
  80817. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80818. if (!url) {
  80819. return _this;
  80820. }
  80821. _this.name = url;
  80822. _this.url = url;
  80823. _this.hasAlpha = false;
  80824. _this.isCube = true;
  80825. _this._textureMatrix = BABYLON.Matrix.Identity();
  80826. _this._onLoad = onLoad;
  80827. _this._onError = onError;
  80828. _this.gammaSpace = gammaSpace;
  80829. _this._noMipmap = noMipmap;
  80830. _this._size = size;
  80831. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80832. if (!_this._texture) {
  80833. if (!scene.useDelayedTextureLoading) {
  80834. _this.loadTexture();
  80835. }
  80836. else {
  80837. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80838. }
  80839. }
  80840. return _this;
  80841. }
  80842. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80843. /**
  80844. * Gets wether or not the texture is blocking during loading.
  80845. */
  80846. get: function () {
  80847. return this._isBlocking;
  80848. },
  80849. /**
  80850. * Sets wether or not the texture is blocking during loading.
  80851. */
  80852. set: function (value) {
  80853. this._isBlocking = value;
  80854. },
  80855. enumerable: true,
  80856. configurable: true
  80857. });
  80858. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80859. /**
  80860. * Gets texture matrix rotation angle around Y axis radians.
  80861. */
  80862. get: function () {
  80863. return this._rotationY;
  80864. },
  80865. /**
  80866. * Sets texture matrix rotation angle around Y axis in radians.
  80867. */
  80868. set: function (value) {
  80869. this._rotationY = value;
  80870. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80871. },
  80872. enumerable: true,
  80873. configurable: true
  80874. });
  80875. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80876. get: function () {
  80877. return this._boundingBoxSize;
  80878. },
  80879. /**
  80880. * Gets or sets the size of the bounding box associated with the cube texture
  80881. * When defined, the cubemap will switch to local mode
  80882. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80883. * @example https://www.babylonjs-playground.com/#RNASML
  80884. */
  80885. set: function (value) {
  80886. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80887. return;
  80888. }
  80889. this._boundingBoxSize = value;
  80890. var scene = this.getScene();
  80891. if (scene) {
  80892. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80893. }
  80894. },
  80895. enumerable: true,
  80896. configurable: true
  80897. });
  80898. /**
  80899. * Occurs when the file is raw .hdr file.
  80900. */
  80901. HDRCubeTexture.prototype.loadTexture = function () {
  80902. var _this = this;
  80903. var callback = function (buffer) {
  80904. var scene = _this.getScene();
  80905. if (!scene) {
  80906. return null;
  80907. }
  80908. // Extract the raw linear data.
  80909. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80910. // Generate harmonics if needed.
  80911. if (_this._generateHarmonics) {
  80912. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80913. _this.sphericalPolynomial = sphericalPolynomial;
  80914. }
  80915. var results = [];
  80916. var byteArray = null;
  80917. // Push each faces.
  80918. for (var j = 0; j < 6; j++) {
  80919. // Create uintarray fallback.
  80920. if (!scene.getEngine().getCaps().textureFloat) {
  80921. // 3 channels of 1 bytes per pixel in bytes.
  80922. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80923. byteArray = new Uint8Array(byteBuffer);
  80924. }
  80925. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80926. // If special cases.
  80927. if (_this.gammaSpace || byteArray) {
  80928. for (var i = 0; i < _this._size * _this._size; i++) {
  80929. // Put in gamma space if requested.
  80930. if (_this.gammaSpace) {
  80931. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80932. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80933. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80934. }
  80935. // Convert to int texture for fallback.
  80936. if (byteArray) {
  80937. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80938. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80939. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80940. // May use luminance instead if the result is not accurate.
  80941. var max = Math.max(Math.max(r, g), b);
  80942. if (max > 255) {
  80943. var scale = 255 / max;
  80944. r *= scale;
  80945. g *= scale;
  80946. b *= scale;
  80947. }
  80948. byteArray[(i * 3) + 0] = r;
  80949. byteArray[(i * 3) + 1] = g;
  80950. byteArray[(i * 3) + 2] = b;
  80951. }
  80952. }
  80953. }
  80954. if (byteArray) {
  80955. results.push(byteArray);
  80956. }
  80957. else {
  80958. results.push(dataFace);
  80959. }
  80960. }
  80961. return results;
  80962. };
  80963. var scene = this.getScene();
  80964. if (scene) {
  80965. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  80966. }
  80967. };
  80968. HDRCubeTexture.prototype.clone = function () {
  80969. var scene = this.getScene();
  80970. if (!scene) {
  80971. return this;
  80972. }
  80973. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80974. // Base texture
  80975. newTexture.level = this.level;
  80976. newTexture.wrapU = this.wrapU;
  80977. newTexture.wrapV = this.wrapV;
  80978. newTexture.coordinatesIndex = this.coordinatesIndex;
  80979. newTexture.coordinatesMode = this.coordinatesMode;
  80980. return newTexture;
  80981. };
  80982. // Methods
  80983. HDRCubeTexture.prototype.delayLoad = function () {
  80984. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80985. return;
  80986. }
  80987. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80988. this._texture = this._getFromCache(this.url, this._noMipmap);
  80989. if (!this._texture) {
  80990. this.loadTexture();
  80991. }
  80992. };
  80993. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80994. return this._textureMatrix;
  80995. };
  80996. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80997. this._textureMatrix = value;
  80998. };
  80999. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81000. var texture = null;
  81001. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81002. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81003. texture.name = parsedTexture.name;
  81004. texture.hasAlpha = parsedTexture.hasAlpha;
  81005. texture.level = parsedTexture.level;
  81006. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81007. texture.isBlocking = parsedTexture.isBlocking;
  81008. }
  81009. if (texture) {
  81010. if (parsedTexture.boundingBoxPosition) {
  81011. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81012. }
  81013. if (parsedTexture.boundingBoxSize) {
  81014. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81015. }
  81016. if (parsedTexture.rotationY) {
  81017. texture.rotationY = parsedTexture.rotationY;
  81018. }
  81019. }
  81020. return texture;
  81021. };
  81022. HDRCubeTexture.prototype.serialize = function () {
  81023. if (!this.name) {
  81024. return null;
  81025. }
  81026. var serializationObject = {};
  81027. serializationObject.name = this.name;
  81028. serializationObject.hasAlpha = this.hasAlpha;
  81029. serializationObject.isCube = true;
  81030. serializationObject.level = this.level;
  81031. serializationObject.size = this._size;
  81032. serializationObject.coordinatesMode = this.coordinatesMode;
  81033. serializationObject.useInGammaSpace = this.gammaSpace;
  81034. serializationObject.generateHarmonics = this._generateHarmonics;
  81035. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81036. serializationObject.noMipmap = this._noMipmap;
  81037. serializationObject.isBlocking = this._isBlocking;
  81038. serializationObject.rotationY = this._rotationY;
  81039. return serializationObject;
  81040. };
  81041. HDRCubeTexture._facesMapping = [
  81042. "right",
  81043. "left",
  81044. "up",
  81045. "down",
  81046. "front",
  81047. "back"
  81048. ];
  81049. return HDRCubeTexture;
  81050. }(BABYLON.BaseTexture));
  81051. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81052. })(BABYLON || (BABYLON = {}));
  81053. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81054. var BABYLON;
  81055. (function (BABYLON) {
  81056. var IndexedVector2 = /** @class */ (function (_super) {
  81057. __extends(IndexedVector2, _super);
  81058. function IndexedVector2(original, index) {
  81059. var _this = _super.call(this, original.x, original.y) || this;
  81060. _this.index = index;
  81061. return _this;
  81062. }
  81063. return IndexedVector2;
  81064. }(BABYLON.Vector2));
  81065. var PolygonPoints = /** @class */ (function () {
  81066. function PolygonPoints() {
  81067. this.elements = new Array();
  81068. }
  81069. PolygonPoints.prototype.add = function (originalPoints) {
  81070. var _this = this;
  81071. var result = new Array();
  81072. originalPoints.forEach(function (point) {
  81073. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81074. var newPoint = new IndexedVector2(point, _this.elements.length);
  81075. result.push(newPoint);
  81076. _this.elements.push(newPoint);
  81077. }
  81078. });
  81079. return result;
  81080. };
  81081. PolygonPoints.prototype.computeBounds = function () {
  81082. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81083. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81084. this.elements.forEach(function (point) {
  81085. // x
  81086. if (point.x < lmin.x) {
  81087. lmin.x = point.x;
  81088. }
  81089. else if (point.x > lmax.x) {
  81090. lmax.x = point.x;
  81091. }
  81092. // y
  81093. if (point.y < lmin.y) {
  81094. lmin.y = point.y;
  81095. }
  81096. else if (point.y > lmax.y) {
  81097. lmax.y = point.y;
  81098. }
  81099. });
  81100. return {
  81101. min: lmin,
  81102. max: lmax,
  81103. width: lmax.x - lmin.x,
  81104. height: lmax.y - lmin.y
  81105. };
  81106. };
  81107. return PolygonPoints;
  81108. }());
  81109. var Polygon = /** @class */ (function () {
  81110. function Polygon() {
  81111. }
  81112. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81113. return [
  81114. new BABYLON.Vector2(xmin, ymin),
  81115. new BABYLON.Vector2(xmax, ymin),
  81116. new BABYLON.Vector2(xmax, ymax),
  81117. new BABYLON.Vector2(xmin, ymax)
  81118. ];
  81119. };
  81120. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81121. if (cx === void 0) { cx = 0; }
  81122. if (cy === void 0) { cy = 0; }
  81123. if (numberOfSides === void 0) { numberOfSides = 32; }
  81124. var result = new Array();
  81125. var angle = 0;
  81126. var increment = (Math.PI * 2) / numberOfSides;
  81127. for (var i = 0; i < numberOfSides; i++) {
  81128. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81129. angle -= increment;
  81130. }
  81131. return result;
  81132. };
  81133. Polygon.Parse = function (input) {
  81134. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81135. var i, result = [];
  81136. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81137. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81138. }
  81139. return result;
  81140. };
  81141. Polygon.StartingAt = function (x, y) {
  81142. return BABYLON.Path2.StartingAt(x, y);
  81143. };
  81144. return Polygon;
  81145. }());
  81146. BABYLON.Polygon = Polygon;
  81147. var PolygonMeshBuilder = /** @class */ (function () {
  81148. function PolygonMeshBuilder(name, contours, scene) {
  81149. this._points = new PolygonPoints();
  81150. this._outlinepoints = new PolygonPoints();
  81151. this._holes = new Array();
  81152. this._epoints = new Array();
  81153. this._eholes = new Array();
  81154. this._name = name;
  81155. this._scene = scene;
  81156. var points;
  81157. if (contours instanceof BABYLON.Path2) {
  81158. points = contours.getPoints();
  81159. }
  81160. else {
  81161. points = contours;
  81162. }
  81163. this._addToepoint(points);
  81164. this._points.add(points);
  81165. this._outlinepoints.add(points);
  81166. if (typeof earcut === 'undefined') {
  81167. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81168. }
  81169. }
  81170. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81171. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81172. var p = points_1[_i];
  81173. this._epoints.push(p.x, p.y);
  81174. }
  81175. };
  81176. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81177. this._points.add(hole);
  81178. var holepoints = new PolygonPoints();
  81179. holepoints.add(hole);
  81180. this._holes.push(holepoints);
  81181. this._eholes.push(this._epoints.length / 2);
  81182. this._addToepoint(hole);
  81183. return this;
  81184. };
  81185. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81186. var _this = this;
  81187. if (updatable === void 0) { updatable = false; }
  81188. if (depth === void 0) { depth = 0; }
  81189. var result = new BABYLON.Mesh(this._name, this._scene);
  81190. var normals = new Array();
  81191. var positions = new Array();
  81192. var uvs = new Array();
  81193. var bounds = this._points.computeBounds();
  81194. this._points.elements.forEach(function (p) {
  81195. normals.push(0, 1.0, 0);
  81196. positions.push(p.x, 0, p.y);
  81197. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81198. });
  81199. var indices = new Array();
  81200. var res = earcut(this._epoints, this._eholes, 2);
  81201. for (var i = 0; i < res.length; i++) {
  81202. indices.push(res[i]);
  81203. }
  81204. if (depth > 0) {
  81205. var positionscount = (positions.length / 3); //get the current pointcount
  81206. this._points.elements.forEach(function (p) {
  81207. normals.push(0, -1.0, 0);
  81208. positions.push(p.x, -depth, p.y);
  81209. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81210. });
  81211. var totalCount = indices.length;
  81212. for (var i = 0; i < totalCount; i += 3) {
  81213. var i0 = indices[i + 0];
  81214. var i1 = indices[i + 1];
  81215. var i2 = indices[i + 2];
  81216. indices.push(i2 + positionscount);
  81217. indices.push(i1 + positionscount);
  81218. indices.push(i0 + positionscount);
  81219. }
  81220. //Add the sides
  81221. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81222. this._holes.forEach(function (hole) {
  81223. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81224. });
  81225. }
  81226. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81227. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81228. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81229. result.setIndices(indices);
  81230. return result;
  81231. };
  81232. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81233. var StartIndex = positions.length / 3;
  81234. var ulength = 0;
  81235. for (var i = 0; i < points.elements.length; i++) {
  81236. var p = points.elements[i];
  81237. var p1;
  81238. if ((i + 1) > points.elements.length - 1) {
  81239. p1 = points.elements[0];
  81240. }
  81241. else {
  81242. p1 = points.elements[i + 1];
  81243. }
  81244. positions.push(p.x, 0, p.y);
  81245. positions.push(p.x, -depth, p.y);
  81246. positions.push(p1.x, 0, p1.y);
  81247. positions.push(p1.x, -depth, p1.y);
  81248. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81249. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81250. var v3 = v2.subtract(v1);
  81251. var v4 = new BABYLON.Vector3(0, 1, 0);
  81252. var vn = BABYLON.Vector3.Cross(v3, v4);
  81253. vn = vn.normalize();
  81254. uvs.push(ulength / bounds.width, 0);
  81255. uvs.push(ulength / bounds.width, 1);
  81256. ulength += v3.length();
  81257. uvs.push((ulength / bounds.width), 0);
  81258. uvs.push((ulength / bounds.width), 1);
  81259. if (!flip) {
  81260. normals.push(-vn.x, -vn.y, -vn.z);
  81261. normals.push(-vn.x, -vn.y, -vn.z);
  81262. normals.push(-vn.x, -vn.y, -vn.z);
  81263. normals.push(-vn.x, -vn.y, -vn.z);
  81264. indices.push(StartIndex);
  81265. indices.push(StartIndex + 1);
  81266. indices.push(StartIndex + 2);
  81267. indices.push(StartIndex + 1);
  81268. indices.push(StartIndex + 3);
  81269. indices.push(StartIndex + 2);
  81270. }
  81271. else {
  81272. normals.push(vn.x, vn.y, vn.z);
  81273. normals.push(vn.x, vn.y, vn.z);
  81274. normals.push(vn.x, vn.y, vn.z);
  81275. normals.push(vn.x, vn.y, vn.z);
  81276. indices.push(StartIndex);
  81277. indices.push(StartIndex + 2);
  81278. indices.push(StartIndex + 1);
  81279. indices.push(StartIndex + 1);
  81280. indices.push(StartIndex + 2);
  81281. indices.push(StartIndex + 3);
  81282. }
  81283. StartIndex += 4;
  81284. }
  81285. ;
  81286. };
  81287. return PolygonMeshBuilder;
  81288. }());
  81289. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81290. })(BABYLON || (BABYLON = {}));
  81291. //# sourceMappingURL=babylon.polygonMesh.js.map
  81292. var BABYLON;
  81293. (function (BABYLON) {
  81294. // Unique ID when we import meshes from Babylon to CSG
  81295. var currentCSGMeshId = 0;
  81296. // # class Vertex
  81297. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81298. // one to provide additional features like texture coordinates and vertex
  81299. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81300. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81301. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81302. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81303. // is not used anywhere else.
  81304. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81305. var Vertex = /** @class */ (function () {
  81306. function Vertex(pos, normal, uv) {
  81307. this.pos = pos;
  81308. this.normal = normal;
  81309. this.uv = uv;
  81310. }
  81311. Vertex.prototype.clone = function () {
  81312. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81313. };
  81314. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81315. // orientation of a polygon is flipped.
  81316. Vertex.prototype.flip = function () {
  81317. this.normal = this.normal.scale(-1);
  81318. };
  81319. // Create a new vertex between this vertex and `other` by linearly
  81320. // interpolating all properties using a parameter of `t`. Subclasses should
  81321. // override this to interpolate additional properties.
  81322. Vertex.prototype.interpolate = function (other, t) {
  81323. 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));
  81324. };
  81325. return Vertex;
  81326. }());
  81327. // # class Plane
  81328. // Represents a plane in 3D space.
  81329. var Plane = /** @class */ (function () {
  81330. function Plane(normal, w) {
  81331. this.normal = normal;
  81332. this.w = w;
  81333. }
  81334. Plane.FromPoints = function (a, b, c) {
  81335. var v0 = c.subtract(a);
  81336. var v1 = b.subtract(a);
  81337. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81338. return null;
  81339. }
  81340. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81341. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81342. };
  81343. Plane.prototype.clone = function () {
  81344. return new Plane(this.normal.clone(), this.w);
  81345. };
  81346. Plane.prototype.flip = function () {
  81347. this.normal.scaleInPlace(-1);
  81348. this.w = -this.w;
  81349. };
  81350. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81351. // fragments in the appropriate lists. Coplanar polygons go into either
  81352. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81353. // respect to this plane. Polygons in front or in back of this plane go into
  81354. // either `front` or `back`.
  81355. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81356. var COPLANAR = 0;
  81357. var FRONT = 1;
  81358. var BACK = 2;
  81359. var SPANNING = 3;
  81360. // Classify each point as well as the entire polygon into one of the above
  81361. // four classes.
  81362. var polygonType = 0;
  81363. var types = [];
  81364. var i;
  81365. var t;
  81366. for (i = 0; i < polygon.vertices.length; i++) {
  81367. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81368. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81369. polygonType |= type;
  81370. types.push(type);
  81371. }
  81372. // Put the polygon in the correct list, splitting it when necessary.
  81373. switch (polygonType) {
  81374. case COPLANAR:
  81375. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81376. break;
  81377. case FRONT:
  81378. front.push(polygon);
  81379. break;
  81380. case BACK:
  81381. back.push(polygon);
  81382. break;
  81383. case SPANNING:
  81384. var f = [], b = [];
  81385. for (i = 0; i < polygon.vertices.length; i++) {
  81386. var j = (i + 1) % polygon.vertices.length;
  81387. var ti = types[i], tj = types[j];
  81388. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81389. if (ti !== BACK)
  81390. f.push(vi);
  81391. if (ti !== FRONT)
  81392. b.push(ti !== BACK ? vi.clone() : vi);
  81393. if ((ti | tj) === SPANNING) {
  81394. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81395. var v = vi.interpolate(vj, t);
  81396. f.push(v);
  81397. b.push(v.clone());
  81398. }
  81399. }
  81400. var poly;
  81401. if (f.length >= 3) {
  81402. poly = new Polygon(f, polygon.shared);
  81403. if (poly.plane)
  81404. front.push(poly);
  81405. }
  81406. if (b.length >= 3) {
  81407. poly = new Polygon(b, polygon.shared);
  81408. if (poly.plane)
  81409. back.push(poly);
  81410. }
  81411. break;
  81412. }
  81413. };
  81414. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81415. // point is on the plane.
  81416. Plane.EPSILON = 1e-5;
  81417. return Plane;
  81418. }());
  81419. // # class Polygon
  81420. // Represents a convex polygon. The vertices used to initialize a polygon must
  81421. // be coplanar and form a convex loop.
  81422. //
  81423. // Each convex polygon has a `shared` property, which is shared between all
  81424. // polygons that are clones of each other or were split from the same polygon.
  81425. // This can be used to define per-polygon properties (such as surface color).
  81426. var Polygon = /** @class */ (function () {
  81427. function Polygon(vertices, shared) {
  81428. this.vertices = vertices;
  81429. this.shared = shared;
  81430. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81431. }
  81432. Polygon.prototype.clone = function () {
  81433. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81434. return new Polygon(vertices, this.shared);
  81435. };
  81436. Polygon.prototype.flip = function () {
  81437. this.vertices.reverse().map(function (v) { v.flip(); });
  81438. this.plane.flip();
  81439. };
  81440. return Polygon;
  81441. }());
  81442. // # class Node
  81443. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81444. // by picking a polygon to split along. That polygon (and all other coplanar
  81445. // polygons) are added directly to that node and the other polygons are added to
  81446. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81447. // no distinction between internal and leaf nodes.
  81448. var Node = /** @class */ (function () {
  81449. function Node(polygons) {
  81450. this.plane = null;
  81451. this.front = null;
  81452. this.back = null;
  81453. this.polygons = new Array();
  81454. if (polygons) {
  81455. this.build(polygons);
  81456. }
  81457. }
  81458. Node.prototype.clone = function () {
  81459. var node = new Node();
  81460. node.plane = this.plane && this.plane.clone();
  81461. node.front = this.front && this.front.clone();
  81462. node.back = this.back && this.back.clone();
  81463. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81464. return node;
  81465. };
  81466. // Convert solid space to empty space and empty space to solid space.
  81467. Node.prototype.invert = function () {
  81468. for (var i = 0; i < this.polygons.length; i++) {
  81469. this.polygons[i].flip();
  81470. }
  81471. if (this.plane) {
  81472. this.plane.flip();
  81473. }
  81474. if (this.front) {
  81475. this.front.invert();
  81476. }
  81477. if (this.back) {
  81478. this.back.invert();
  81479. }
  81480. var temp = this.front;
  81481. this.front = this.back;
  81482. this.back = temp;
  81483. };
  81484. // Recursively remove all polygons in `polygons` that are inside this BSP
  81485. // tree.
  81486. Node.prototype.clipPolygons = function (polygons) {
  81487. if (!this.plane)
  81488. return polygons.slice();
  81489. var front = new Array(), back = new Array();
  81490. for (var i = 0; i < polygons.length; i++) {
  81491. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81492. }
  81493. if (this.front) {
  81494. front = this.front.clipPolygons(front);
  81495. }
  81496. if (this.back) {
  81497. back = this.back.clipPolygons(back);
  81498. }
  81499. else {
  81500. back = [];
  81501. }
  81502. return front.concat(back);
  81503. };
  81504. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81505. // `bsp`.
  81506. Node.prototype.clipTo = function (bsp) {
  81507. this.polygons = bsp.clipPolygons(this.polygons);
  81508. if (this.front)
  81509. this.front.clipTo(bsp);
  81510. if (this.back)
  81511. this.back.clipTo(bsp);
  81512. };
  81513. // Return a list of all polygons in this BSP tree.
  81514. Node.prototype.allPolygons = function () {
  81515. var polygons = this.polygons.slice();
  81516. if (this.front)
  81517. polygons = polygons.concat(this.front.allPolygons());
  81518. if (this.back)
  81519. polygons = polygons.concat(this.back.allPolygons());
  81520. return polygons;
  81521. };
  81522. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81523. // new polygons are filtered down to the bottom of the tree and become new
  81524. // nodes there. Each set of polygons is partitioned using the first polygon
  81525. // (no heuristic is used to pick a good split).
  81526. Node.prototype.build = function (polygons) {
  81527. if (!polygons.length)
  81528. return;
  81529. if (!this.plane)
  81530. this.plane = polygons[0].plane.clone();
  81531. var front = new Array(), back = new Array();
  81532. for (var i = 0; i < polygons.length; i++) {
  81533. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81534. }
  81535. if (front.length) {
  81536. if (!this.front)
  81537. this.front = new Node();
  81538. this.front.build(front);
  81539. }
  81540. if (back.length) {
  81541. if (!this.back)
  81542. this.back = new Node();
  81543. this.back.build(back);
  81544. }
  81545. };
  81546. return Node;
  81547. }());
  81548. var CSG = /** @class */ (function () {
  81549. function CSG() {
  81550. this.polygons = new Array();
  81551. }
  81552. // Convert BABYLON.Mesh to BABYLON.CSG
  81553. CSG.FromMesh = function (mesh) {
  81554. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81555. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81556. if (mesh instanceof BABYLON.Mesh) {
  81557. mesh.computeWorldMatrix(true);
  81558. matrix = mesh.getWorldMatrix();
  81559. meshPosition = mesh.position.clone();
  81560. meshRotation = mesh.rotation.clone();
  81561. if (mesh.rotationQuaternion) {
  81562. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81563. }
  81564. meshScaling = mesh.scaling.clone();
  81565. }
  81566. else {
  81567. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81568. }
  81569. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81570. var subMeshes = mesh.subMeshes;
  81571. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81572. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81573. vertices = [];
  81574. for (var j = 0; j < 3; j++) {
  81575. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81576. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81577. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81578. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81579. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81580. vertex = new Vertex(position, normal, uv);
  81581. vertices.push(vertex);
  81582. }
  81583. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81584. // To handle the case of degenerated triangle
  81585. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81586. if (polygon.plane)
  81587. polygons.push(polygon);
  81588. }
  81589. }
  81590. var csg = CSG.FromPolygons(polygons);
  81591. csg.matrix = matrix;
  81592. csg.position = meshPosition;
  81593. csg.rotation = meshRotation;
  81594. csg.scaling = meshScaling;
  81595. csg.rotationQuaternion = meshRotationQuaternion;
  81596. currentCSGMeshId++;
  81597. return csg;
  81598. };
  81599. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81600. CSG.FromPolygons = function (polygons) {
  81601. var csg = new CSG();
  81602. csg.polygons = polygons;
  81603. return csg;
  81604. };
  81605. CSG.prototype.clone = function () {
  81606. var csg = new CSG();
  81607. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81608. csg.copyTransformAttributes(this);
  81609. return csg;
  81610. };
  81611. CSG.prototype.union = function (csg) {
  81612. var a = new Node(this.clone().polygons);
  81613. var b = new Node(csg.clone().polygons);
  81614. a.clipTo(b);
  81615. b.clipTo(a);
  81616. b.invert();
  81617. b.clipTo(a);
  81618. b.invert();
  81619. a.build(b.allPolygons());
  81620. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81621. };
  81622. CSG.prototype.unionInPlace = function (csg) {
  81623. var a = new Node(this.polygons);
  81624. var b = new Node(csg.polygons);
  81625. a.clipTo(b);
  81626. b.clipTo(a);
  81627. b.invert();
  81628. b.clipTo(a);
  81629. b.invert();
  81630. a.build(b.allPolygons());
  81631. this.polygons = a.allPolygons();
  81632. };
  81633. CSG.prototype.subtract = function (csg) {
  81634. var a = new Node(this.clone().polygons);
  81635. var b = new Node(csg.clone().polygons);
  81636. a.invert();
  81637. a.clipTo(b);
  81638. b.clipTo(a);
  81639. b.invert();
  81640. b.clipTo(a);
  81641. b.invert();
  81642. a.build(b.allPolygons());
  81643. a.invert();
  81644. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81645. };
  81646. CSG.prototype.subtractInPlace = function (csg) {
  81647. var a = new Node(this.polygons);
  81648. var b = new Node(csg.polygons);
  81649. a.invert();
  81650. a.clipTo(b);
  81651. b.clipTo(a);
  81652. b.invert();
  81653. b.clipTo(a);
  81654. b.invert();
  81655. a.build(b.allPolygons());
  81656. a.invert();
  81657. this.polygons = a.allPolygons();
  81658. };
  81659. CSG.prototype.intersect = function (csg) {
  81660. var a = new Node(this.clone().polygons);
  81661. var b = new Node(csg.clone().polygons);
  81662. a.invert();
  81663. b.clipTo(a);
  81664. b.invert();
  81665. a.clipTo(b);
  81666. b.clipTo(a);
  81667. a.build(b.allPolygons());
  81668. a.invert();
  81669. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81670. };
  81671. CSG.prototype.intersectInPlace = function (csg) {
  81672. var a = new Node(this.polygons);
  81673. var b = new Node(csg.polygons);
  81674. a.invert();
  81675. b.clipTo(a);
  81676. b.invert();
  81677. a.clipTo(b);
  81678. b.clipTo(a);
  81679. a.build(b.allPolygons());
  81680. a.invert();
  81681. this.polygons = a.allPolygons();
  81682. };
  81683. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81684. // not modified.
  81685. CSG.prototype.inverse = function () {
  81686. var csg = this.clone();
  81687. csg.inverseInPlace();
  81688. return csg;
  81689. };
  81690. CSG.prototype.inverseInPlace = function () {
  81691. this.polygons.map(function (p) { p.flip(); });
  81692. };
  81693. // This is used to keep meshes transformations so they can be restored
  81694. // when we build back a Babylon Mesh
  81695. // NB : All CSG operations are performed in world coordinates
  81696. CSG.prototype.copyTransformAttributes = function (csg) {
  81697. this.matrix = csg.matrix;
  81698. this.position = csg.position;
  81699. this.rotation = csg.rotation;
  81700. this.scaling = csg.scaling;
  81701. this.rotationQuaternion = csg.rotationQuaternion;
  81702. return this;
  81703. };
  81704. // Build Raw mesh from CSG
  81705. // Coordinates here are in world space
  81706. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81707. var matrix = this.matrix.clone();
  81708. matrix.invert();
  81709. 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;
  81710. if (keepSubMeshes) {
  81711. // Sort Polygons, since subMeshes are indices range
  81712. polygons.sort(function (a, b) {
  81713. if (a.shared.meshId === b.shared.meshId) {
  81714. return a.shared.subMeshId - b.shared.subMeshId;
  81715. }
  81716. else {
  81717. return a.shared.meshId - b.shared.meshId;
  81718. }
  81719. });
  81720. }
  81721. for (var i = 0, il = polygons.length; i < il; i++) {
  81722. polygon = polygons[i];
  81723. // Building SubMeshes
  81724. if (!subMesh_dict[polygon.shared.meshId]) {
  81725. subMesh_dict[polygon.shared.meshId] = {};
  81726. }
  81727. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81728. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81729. indexStart: +Infinity,
  81730. indexEnd: -Infinity,
  81731. materialIndex: polygon.shared.materialIndex
  81732. };
  81733. }
  81734. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81735. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81736. polygonIndices[0] = 0;
  81737. polygonIndices[1] = j - 1;
  81738. polygonIndices[2] = j;
  81739. for (var k = 0; k < 3; k++) {
  81740. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81741. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81742. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81743. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81744. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81745. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81746. // Check if 2 points can be merged
  81747. if (!(typeof vertex_idx !== 'undefined' &&
  81748. normals[vertex_idx * 3] === localNormal.x &&
  81749. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81750. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81751. uvs[vertex_idx * 2] === uv.x &&
  81752. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81753. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81754. uvs.push(uv.x, uv.y);
  81755. normals.push(normal.x, normal.y, normal.z);
  81756. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81757. }
  81758. indices.push(vertex_idx);
  81759. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81760. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81761. currentIndex++;
  81762. }
  81763. }
  81764. }
  81765. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81766. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81767. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81768. mesh.setIndices(indices, null);
  81769. if (keepSubMeshes) {
  81770. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81771. var materialIndexOffset = 0, materialMaxIndex;
  81772. mesh.subMeshes = new Array();
  81773. for (var m in subMesh_dict) {
  81774. materialMaxIndex = -1;
  81775. for (var sm in subMesh_dict[m]) {
  81776. subMesh_obj = subMesh_dict[m][sm];
  81777. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81778. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81779. }
  81780. materialIndexOffset += ++materialMaxIndex;
  81781. }
  81782. }
  81783. return mesh;
  81784. };
  81785. // Build Mesh from CSG taking material and transforms into account
  81786. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81787. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81788. mesh.material = material;
  81789. mesh.position.copyFrom(this.position);
  81790. mesh.rotation.copyFrom(this.rotation);
  81791. if (this.rotationQuaternion) {
  81792. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81793. }
  81794. mesh.scaling.copyFrom(this.scaling);
  81795. mesh.computeWorldMatrix(true);
  81796. return mesh;
  81797. };
  81798. return CSG;
  81799. }());
  81800. BABYLON.CSG = CSG;
  81801. })(BABYLON || (BABYLON = {}));
  81802. //# sourceMappingURL=babylon.csg.js.map
  81803. var BABYLON;
  81804. (function (BABYLON) {
  81805. var LensFlare = /** @class */ (function () {
  81806. function LensFlare(size, position, color, imgUrl, system) {
  81807. this.size = size;
  81808. this.position = position;
  81809. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81810. this.color = color || new BABYLON.Color3(1, 1, 1);
  81811. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81812. this._system = system;
  81813. system.lensFlares.push(this);
  81814. }
  81815. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81816. return new LensFlare(size, position, color, imgUrl, system);
  81817. };
  81818. LensFlare.prototype.dispose = function () {
  81819. if (this.texture) {
  81820. this.texture.dispose();
  81821. }
  81822. // Remove from scene
  81823. var index = this._system.lensFlares.indexOf(this);
  81824. this._system.lensFlares.splice(index, 1);
  81825. };
  81826. ;
  81827. return LensFlare;
  81828. }());
  81829. BABYLON.LensFlare = LensFlare;
  81830. })(BABYLON || (BABYLON = {}));
  81831. //# sourceMappingURL=babylon.lensFlare.js.map
  81832. var BABYLON;
  81833. (function (BABYLON) {
  81834. var LensFlareSystem = /** @class */ (function () {
  81835. function LensFlareSystem(name, emitter, scene) {
  81836. this.name = name;
  81837. this.lensFlares = new Array();
  81838. this.borderLimit = 300;
  81839. this.viewportBorder = 0;
  81840. this.layerMask = 0x0FFFFFFF;
  81841. this._vertexBuffers = {};
  81842. this._isEnabled = true;
  81843. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81844. this._emitter = emitter;
  81845. this.id = name;
  81846. scene.lensFlareSystems.push(this);
  81847. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81848. var engine = scene.getEngine();
  81849. // VBO
  81850. var vertices = [];
  81851. vertices.push(1, 1);
  81852. vertices.push(-1, 1);
  81853. vertices.push(-1, -1);
  81854. vertices.push(1, -1);
  81855. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81856. // Indices
  81857. var indices = [];
  81858. indices.push(0);
  81859. indices.push(1);
  81860. indices.push(2);
  81861. indices.push(0);
  81862. indices.push(2);
  81863. indices.push(3);
  81864. this._indexBuffer = engine.createIndexBuffer(indices);
  81865. // Effects
  81866. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81867. }
  81868. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81869. get: function () {
  81870. return this._isEnabled;
  81871. },
  81872. set: function (value) {
  81873. this._isEnabled = value;
  81874. },
  81875. enumerable: true,
  81876. configurable: true
  81877. });
  81878. LensFlareSystem.prototype.getScene = function () {
  81879. return this._scene;
  81880. };
  81881. LensFlareSystem.prototype.getEmitter = function () {
  81882. return this._emitter;
  81883. };
  81884. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81885. this._emitter = newEmitter;
  81886. };
  81887. LensFlareSystem.prototype.getEmitterPosition = function () {
  81888. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81889. };
  81890. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81891. var position = this.getEmitterPosition();
  81892. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81893. this._positionX = position.x;
  81894. this._positionY = position.y;
  81895. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81896. if (this.viewportBorder > 0) {
  81897. globalViewport.x -= this.viewportBorder;
  81898. globalViewport.y -= this.viewportBorder;
  81899. globalViewport.width += this.viewportBorder * 2;
  81900. globalViewport.height += this.viewportBorder * 2;
  81901. position.x += this.viewportBorder;
  81902. position.y += this.viewportBorder;
  81903. this._positionX += this.viewportBorder;
  81904. this._positionY += this.viewportBorder;
  81905. }
  81906. if (position.z > 0) {
  81907. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81908. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81909. return true;
  81910. }
  81911. return true;
  81912. }
  81913. return false;
  81914. };
  81915. LensFlareSystem.prototype._isVisible = function () {
  81916. if (!this._isEnabled || !this._scene.activeCamera) {
  81917. return false;
  81918. }
  81919. var emitterPosition = this.getEmitterPosition();
  81920. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81921. var distance = direction.length();
  81922. direction.normalize();
  81923. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81924. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81925. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81926. };
  81927. LensFlareSystem.prototype.render = function () {
  81928. if (!this._effect.isReady() || !this._scene.activeCamera)
  81929. return false;
  81930. var engine = this._scene.getEngine();
  81931. var viewport = this._scene.activeCamera.viewport;
  81932. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81933. // Position
  81934. if (!this.computeEffectivePosition(globalViewport)) {
  81935. return false;
  81936. }
  81937. // Visibility
  81938. if (!this._isVisible()) {
  81939. return false;
  81940. }
  81941. // Intensity
  81942. var awayX;
  81943. var awayY;
  81944. if (this._positionX < this.borderLimit + globalViewport.x) {
  81945. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81946. }
  81947. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81948. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81949. }
  81950. else {
  81951. awayX = 0;
  81952. }
  81953. if (this._positionY < this.borderLimit + globalViewport.y) {
  81954. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81955. }
  81956. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81957. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81958. }
  81959. else {
  81960. awayY = 0;
  81961. }
  81962. var away = (awayX > awayY) ? awayX : awayY;
  81963. away -= this.viewportBorder;
  81964. if (away > this.borderLimit) {
  81965. away = this.borderLimit;
  81966. }
  81967. var intensity = 1.0 - (away / this.borderLimit);
  81968. if (intensity < 0) {
  81969. return false;
  81970. }
  81971. if (intensity > 1.0) {
  81972. intensity = 1.0;
  81973. }
  81974. if (this.viewportBorder > 0) {
  81975. globalViewport.x += this.viewportBorder;
  81976. globalViewport.y += this.viewportBorder;
  81977. globalViewport.width -= this.viewportBorder * 2;
  81978. globalViewport.height -= this.viewportBorder * 2;
  81979. this._positionX -= this.viewportBorder;
  81980. this._positionY -= this.viewportBorder;
  81981. }
  81982. // Position
  81983. var centerX = globalViewport.x + globalViewport.width / 2;
  81984. var centerY = globalViewport.y + globalViewport.height / 2;
  81985. var distX = centerX - this._positionX;
  81986. var distY = centerY - this._positionY;
  81987. // Effects
  81988. engine.enableEffect(this._effect);
  81989. engine.setState(false);
  81990. engine.setDepthBuffer(false);
  81991. // VBOs
  81992. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81993. // Flares
  81994. for (var index = 0; index < this.lensFlares.length; index++) {
  81995. var flare = this.lensFlares[index];
  81996. engine.setAlphaMode(flare.alphaMode);
  81997. var x = centerX - (distX * flare.position);
  81998. var y = centerY - (distY * flare.position);
  81999. var cw = flare.size;
  82000. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82001. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82002. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82003. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82004. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82005. // Texture
  82006. this._effect.setTexture("textureSampler", flare.texture);
  82007. // Color
  82008. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82009. // Draw order
  82010. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82011. }
  82012. engine.setDepthBuffer(true);
  82013. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82014. return true;
  82015. };
  82016. LensFlareSystem.prototype.dispose = function () {
  82017. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82018. if (vertexBuffer) {
  82019. vertexBuffer.dispose();
  82020. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82021. }
  82022. if (this._indexBuffer) {
  82023. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82024. this._indexBuffer = null;
  82025. }
  82026. while (this.lensFlares.length) {
  82027. this.lensFlares[0].dispose();
  82028. }
  82029. // Remove from scene
  82030. var index = this._scene.lensFlareSystems.indexOf(this);
  82031. this._scene.lensFlareSystems.splice(index, 1);
  82032. };
  82033. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82034. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82035. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82036. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82037. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82038. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82039. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82040. var parsedFlare = parsedLensFlareSystem.flares[index];
  82041. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82042. }
  82043. return lensFlareSystem;
  82044. };
  82045. LensFlareSystem.prototype.serialize = function () {
  82046. var serializationObject = {};
  82047. serializationObject.id = this.id;
  82048. serializationObject.name = this.name;
  82049. serializationObject.emitterId = this.getEmitter().id;
  82050. serializationObject.borderLimit = this.borderLimit;
  82051. serializationObject.flares = [];
  82052. for (var index = 0; index < this.lensFlares.length; index++) {
  82053. var flare = this.lensFlares[index];
  82054. serializationObject.flares.push({
  82055. size: flare.size,
  82056. position: flare.position,
  82057. color: flare.color.asArray(),
  82058. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82059. });
  82060. }
  82061. return serializationObject;
  82062. };
  82063. return LensFlareSystem;
  82064. }());
  82065. BABYLON.LensFlareSystem = LensFlareSystem;
  82066. })(BABYLON || (BABYLON = {}));
  82067. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82068. var BABYLON;
  82069. (function (BABYLON) {
  82070. /**
  82071. * This is a holder class for the physics joint created by the physics plugin.
  82072. * It holds a set of functions to control the underlying joint.
  82073. */
  82074. var PhysicsJoint = /** @class */ (function () {
  82075. function PhysicsJoint(type, jointData) {
  82076. this.type = type;
  82077. this.jointData = jointData;
  82078. jointData.nativeParams = jointData.nativeParams || {};
  82079. }
  82080. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82081. get: function () {
  82082. return this._physicsJoint;
  82083. },
  82084. set: function (newJoint) {
  82085. if (this._physicsJoint) {
  82086. //remove from the wolrd
  82087. }
  82088. this._physicsJoint = newJoint;
  82089. },
  82090. enumerable: true,
  82091. configurable: true
  82092. });
  82093. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82094. set: function (physicsPlugin) {
  82095. this._physicsPlugin = physicsPlugin;
  82096. },
  82097. enumerable: true,
  82098. configurable: true
  82099. });
  82100. /**
  82101. * Execute a function that is physics-plugin specific.
  82102. * @param {Function} func the function that will be executed.
  82103. * It accepts two parameters: the physics world and the physics joint.
  82104. */
  82105. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82106. func(this._physicsPlugin.world, this._physicsJoint);
  82107. };
  82108. //TODO check if the native joints are the same
  82109. //Joint Types
  82110. PhysicsJoint.DistanceJoint = 0;
  82111. PhysicsJoint.HingeJoint = 1;
  82112. PhysicsJoint.BallAndSocketJoint = 2;
  82113. PhysicsJoint.WheelJoint = 3;
  82114. PhysicsJoint.SliderJoint = 4;
  82115. //OIMO
  82116. PhysicsJoint.PrismaticJoint = 5;
  82117. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82118. PhysicsJoint.UniversalJoint = 6;
  82119. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82120. //Cannon
  82121. //Similar to a Ball-Joint. Different in params
  82122. PhysicsJoint.PointToPointJoint = 8;
  82123. //Cannon only at the moment
  82124. PhysicsJoint.SpringJoint = 9;
  82125. PhysicsJoint.LockJoint = 10;
  82126. return PhysicsJoint;
  82127. }());
  82128. BABYLON.PhysicsJoint = PhysicsJoint;
  82129. /**
  82130. * A class representing a physics distance joint.
  82131. */
  82132. var DistanceJoint = /** @class */ (function (_super) {
  82133. __extends(DistanceJoint, _super);
  82134. function DistanceJoint(jointData) {
  82135. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82136. }
  82137. /**
  82138. * Update the predefined distance.
  82139. */
  82140. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82141. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82142. };
  82143. return DistanceJoint;
  82144. }(PhysicsJoint));
  82145. BABYLON.DistanceJoint = DistanceJoint;
  82146. var MotorEnabledJoint = /** @class */ (function (_super) {
  82147. __extends(MotorEnabledJoint, _super);
  82148. function MotorEnabledJoint(type, jointData) {
  82149. return _super.call(this, type, jointData) || this;
  82150. }
  82151. /**
  82152. * Set the motor values.
  82153. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82154. * @param {number} force the force to apply
  82155. * @param {number} maxForce max force for this motor.
  82156. */
  82157. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82158. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82159. };
  82160. /**
  82161. * Set the motor's limits.
  82162. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82163. */
  82164. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82165. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82166. };
  82167. return MotorEnabledJoint;
  82168. }(PhysicsJoint));
  82169. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82170. /**
  82171. * This class represents a single hinge physics joint
  82172. */
  82173. var HingeJoint = /** @class */ (function (_super) {
  82174. __extends(HingeJoint, _super);
  82175. function HingeJoint(jointData) {
  82176. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82177. }
  82178. /**
  82179. * Set the motor values.
  82180. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82181. * @param {number} force the force to apply
  82182. * @param {number} maxForce max force for this motor.
  82183. */
  82184. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82185. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82186. };
  82187. /**
  82188. * Set the motor's limits.
  82189. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82190. */
  82191. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82192. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82193. };
  82194. return HingeJoint;
  82195. }(MotorEnabledJoint));
  82196. BABYLON.HingeJoint = HingeJoint;
  82197. /**
  82198. * This class represents a dual hinge physics joint (same as wheel joint)
  82199. */
  82200. var Hinge2Joint = /** @class */ (function (_super) {
  82201. __extends(Hinge2Joint, _super);
  82202. function Hinge2Joint(jointData) {
  82203. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82204. }
  82205. /**
  82206. * Set the motor values.
  82207. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82208. * @param {number} force the force to apply
  82209. * @param {number} maxForce max force for this motor.
  82210. * @param {motorIndex} the motor's index, 0 or 1.
  82211. */
  82212. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82213. if (motorIndex === void 0) { motorIndex = 0; }
  82214. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82215. };
  82216. /**
  82217. * Set the motor limits.
  82218. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82219. * @param {number} upperLimit the upper limit
  82220. * @param {number} lowerLimit lower limit
  82221. * @param {motorIndex} the motor's index, 0 or 1.
  82222. */
  82223. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82224. if (motorIndex === void 0) { motorIndex = 0; }
  82225. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82226. };
  82227. return Hinge2Joint;
  82228. }(MotorEnabledJoint));
  82229. BABYLON.Hinge2Joint = Hinge2Joint;
  82230. })(BABYLON || (BABYLON = {}));
  82231. //# sourceMappingURL=babylon.physicsJoint.js.map
  82232. var BABYLON;
  82233. (function (BABYLON) {
  82234. var PhysicsImpostor = /** @class */ (function () {
  82235. function PhysicsImpostor(object, type, _options, _scene) {
  82236. if (_options === void 0) { _options = { mass: 0 }; }
  82237. var _this = this;
  82238. this.object = object;
  82239. this.type = type;
  82240. this._options = _options;
  82241. this._scene = _scene;
  82242. this._bodyUpdateRequired = false;
  82243. this._onBeforePhysicsStepCallbacks = new Array();
  82244. this._onAfterPhysicsStepCallbacks = new Array();
  82245. this._onPhysicsCollideCallbacks = [];
  82246. this._deltaPosition = BABYLON.Vector3.Zero();
  82247. this._isDisposed = false;
  82248. //temp variables for parent rotation calculations
  82249. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82250. this._tmpQuat = new BABYLON.Quaternion();
  82251. this._tmpQuat2 = new BABYLON.Quaternion();
  82252. /**
  82253. * this function is executed by the physics engine.
  82254. */
  82255. this.beforeStep = function () {
  82256. if (!_this._physicsEngine) {
  82257. return;
  82258. }
  82259. _this.object.translate(_this._deltaPosition, -1);
  82260. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82261. _this.object.computeWorldMatrix(false);
  82262. if (_this.object.parent && _this.object.rotationQuaternion) {
  82263. _this.getParentsRotation();
  82264. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82265. }
  82266. else {
  82267. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82268. }
  82269. if (!_this._options.disableBidirectionalTransformation) {
  82270. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  82271. }
  82272. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  82273. func(_this);
  82274. });
  82275. };
  82276. /**
  82277. * this function is executed by the physics engine.
  82278. */
  82279. this.afterStep = function () {
  82280. if (!_this._physicsEngine) {
  82281. return;
  82282. }
  82283. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  82284. func(_this);
  82285. });
  82286. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  82287. // object has now its world rotation. needs to be converted to local.
  82288. if (_this.object.parent && _this.object.rotationQuaternion) {
  82289. _this.getParentsRotation();
  82290. _this._tmpQuat.conjugateInPlace();
  82291. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82292. }
  82293. // take the position set and make it the absolute position of this object.
  82294. _this.object.setAbsolutePosition(_this.object.position);
  82295. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82296. _this.object.translate(_this._deltaPosition, 1);
  82297. };
  82298. /**
  82299. * Legacy collision detection event support
  82300. */
  82301. this.onCollideEvent = null;
  82302. //event and body object due to cannon's event-based architecture.
  82303. this.onCollide = function (e) {
  82304. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82305. return;
  82306. }
  82307. if (!_this._physicsEngine) {
  82308. return;
  82309. }
  82310. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82311. if (otherImpostor) {
  82312. // Legacy collision detection event support
  82313. if (_this.onCollideEvent) {
  82314. _this.onCollideEvent(_this, otherImpostor);
  82315. }
  82316. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82317. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82318. }).forEach(function (obj) {
  82319. obj.callback(_this, otherImpostor);
  82320. });
  82321. }
  82322. };
  82323. //sanity check!
  82324. if (!this.object) {
  82325. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82326. return;
  82327. }
  82328. //legacy support for old syntax.
  82329. if (!this._scene && object.getScene) {
  82330. this._scene = object.getScene();
  82331. }
  82332. if (!this._scene) {
  82333. return;
  82334. }
  82335. this._physicsEngine = this._scene.getPhysicsEngine();
  82336. if (!this._physicsEngine) {
  82337. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82338. }
  82339. else {
  82340. //set the object's quaternion, if not set
  82341. if (!this.object.rotationQuaternion) {
  82342. if (this.object.rotation) {
  82343. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82344. }
  82345. else {
  82346. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82347. }
  82348. }
  82349. //default options params
  82350. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82351. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82352. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82353. this._joints = [];
  82354. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82355. if (!this.object.parent || this._options.ignoreParent) {
  82356. this._init();
  82357. }
  82358. else if (this.object.parent.physicsImpostor) {
  82359. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82360. }
  82361. }
  82362. }
  82363. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82364. get: function () {
  82365. return this._isDisposed;
  82366. },
  82367. enumerable: true,
  82368. configurable: true
  82369. });
  82370. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82371. get: function () {
  82372. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82373. },
  82374. set: function (value) {
  82375. this.setMass(value);
  82376. },
  82377. enumerable: true,
  82378. configurable: true
  82379. });
  82380. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82381. get: function () {
  82382. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82383. },
  82384. set: function (value) {
  82385. if (!this._physicsEngine) {
  82386. return;
  82387. }
  82388. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82389. },
  82390. enumerable: true,
  82391. configurable: true
  82392. });
  82393. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82394. get: function () {
  82395. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82396. },
  82397. set: function (value) {
  82398. if (!this._physicsEngine) {
  82399. return;
  82400. }
  82401. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82402. },
  82403. enumerable: true,
  82404. configurable: true
  82405. });
  82406. /**
  82407. * This function will completly initialize this impostor.
  82408. * It will create a new body - but only if this mesh has no parent.
  82409. * If it has, this impostor will not be used other than to define the impostor
  82410. * of the child mesh.
  82411. */
  82412. PhysicsImpostor.prototype._init = function () {
  82413. if (!this._physicsEngine) {
  82414. return;
  82415. }
  82416. this._physicsEngine.removeImpostor(this);
  82417. this.physicsBody = null;
  82418. this._parent = this._parent || this._getPhysicsParent();
  82419. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82420. this._physicsEngine.addImpostor(this);
  82421. }
  82422. };
  82423. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82424. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82425. var parentMesh = this.object.parent;
  82426. return parentMesh.physicsImpostor;
  82427. }
  82428. return null;
  82429. };
  82430. /**
  82431. * Should a new body be generated.
  82432. */
  82433. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82434. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82435. };
  82436. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82437. this.forceUpdate();
  82438. };
  82439. /**
  82440. * Force a regeneration of this or the parent's impostor's body.
  82441. * Use under cautious - This will remove all joints already implemented.
  82442. */
  82443. PhysicsImpostor.prototype.forceUpdate = function () {
  82444. this._init();
  82445. if (this.parent && !this._options.ignoreParent) {
  82446. this.parent.forceUpdate();
  82447. }
  82448. };
  82449. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82450. /*public get mesh(): AbstractMesh {
  82451. return this._mesh;
  82452. }*/
  82453. /**
  82454. * Gets the body that holds this impostor. Either its own, or its parent.
  82455. */
  82456. get: function () {
  82457. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82458. },
  82459. /**
  82460. * Set the physics body. Used mainly by the physics engine/plugin
  82461. */
  82462. set: function (physicsBody) {
  82463. if (this._physicsBody && this._physicsEngine) {
  82464. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82465. }
  82466. this._physicsBody = physicsBody;
  82467. this.resetUpdateFlags();
  82468. },
  82469. enumerable: true,
  82470. configurable: true
  82471. });
  82472. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82473. get: function () {
  82474. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82475. },
  82476. set: function (value) {
  82477. this._parent = value;
  82478. },
  82479. enumerable: true,
  82480. configurable: true
  82481. });
  82482. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82483. this._bodyUpdateRequired = false;
  82484. };
  82485. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82486. if (this.object.getBoundingInfo) {
  82487. var q = this.object.rotationQuaternion;
  82488. //reset rotation
  82489. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82490. //calculate the world matrix with no rotation
  82491. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82492. var boundingInfo = this.object.getBoundingInfo();
  82493. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82494. //bring back the rotation
  82495. this.object.rotationQuaternion = q;
  82496. //calculate the world matrix with the new rotation
  82497. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82498. return size;
  82499. }
  82500. else {
  82501. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82502. }
  82503. };
  82504. PhysicsImpostor.prototype.getObjectCenter = function () {
  82505. if (this.object.getBoundingInfo) {
  82506. var boundingInfo = this.object.getBoundingInfo();
  82507. return boundingInfo.boundingBox.centerWorld;
  82508. }
  82509. else {
  82510. return this.object.position;
  82511. }
  82512. };
  82513. /**
  82514. * Get a specific parametes from the options parameter.
  82515. */
  82516. PhysicsImpostor.prototype.getParam = function (paramName) {
  82517. return this._options[paramName];
  82518. };
  82519. /**
  82520. * Sets a specific parameter in the options given to the physics plugin
  82521. */
  82522. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82523. this._options[paramName] = value;
  82524. this._bodyUpdateRequired = true;
  82525. };
  82526. /**
  82527. * Specifically change the body's mass option. Won't recreate the physics body object
  82528. */
  82529. PhysicsImpostor.prototype.setMass = function (mass) {
  82530. if (this.getParam("mass") !== mass) {
  82531. this.setParam("mass", mass);
  82532. }
  82533. if (this._physicsEngine) {
  82534. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82535. }
  82536. };
  82537. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82538. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82539. };
  82540. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82541. if (this._physicsEngine) {
  82542. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82543. }
  82544. };
  82545. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82546. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82547. };
  82548. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82549. if (this._physicsEngine) {
  82550. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82551. }
  82552. };
  82553. /**
  82554. * Execute a function with the physics plugin native code.
  82555. * Provide a function the will have two variables - the world object and the physics body object.
  82556. */
  82557. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82558. if (this._physicsEngine) {
  82559. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82560. }
  82561. };
  82562. /**
  82563. * Register a function that will be executed before the physics world is stepping forward.
  82564. */
  82565. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82566. this._onBeforePhysicsStepCallbacks.push(func);
  82567. };
  82568. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82569. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82570. if (index > -1) {
  82571. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82572. }
  82573. else {
  82574. BABYLON.Tools.Warn("Function to remove was not found");
  82575. }
  82576. };
  82577. /**
  82578. * Register a function that will be executed after the physics step
  82579. */
  82580. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82581. this._onAfterPhysicsStepCallbacks.push(func);
  82582. };
  82583. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82584. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82585. if (index > -1) {
  82586. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82587. }
  82588. else {
  82589. BABYLON.Tools.Warn("Function to remove was not found");
  82590. }
  82591. };
  82592. /**
  82593. * register a function that will be executed when this impostor collides against a different body.
  82594. */
  82595. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82596. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82597. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82598. };
  82599. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82600. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82601. var index = -1;
  82602. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82603. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82604. // chcek the arrays match
  82605. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82606. return collidedAgainstList.indexOf(impostor) > -1;
  82607. });
  82608. if (sameList) {
  82609. index = idx;
  82610. }
  82611. return sameList;
  82612. }
  82613. return false;
  82614. });
  82615. if (found) {
  82616. this._onPhysicsCollideCallbacks.splice(index, 1);
  82617. }
  82618. else {
  82619. BABYLON.Tools.Warn("Function to remove was not found");
  82620. }
  82621. };
  82622. PhysicsImpostor.prototype.getParentsRotation = function () {
  82623. var parent = this.object.parent;
  82624. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82625. while (parent) {
  82626. if (parent.rotationQuaternion) {
  82627. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82628. }
  82629. else {
  82630. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82631. }
  82632. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82633. parent = parent.parent;
  82634. }
  82635. return this._tmpQuat;
  82636. };
  82637. /**
  82638. * Apply a force
  82639. */
  82640. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82641. if (this._physicsEngine) {
  82642. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82643. }
  82644. return this;
  82645. };
  82646. /**
  82647. * Apply an impulse
  82648. */
  82649. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82650. if (this._physicsEngine) {
  82651. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82652. }
  82653. return this;
  82654. };
  82655. /**
  82656. * A help function to create a joint.
  82657. */
  82658. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82659. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82660. this.addJoint(otherImpostor, joint);
  82661. return this;
  82662. };
  82663. /**
  82664. * Add a joint to this impostor with a different impostor.
  82665. */
  82666. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82667. this._joints.push({
  82668. otherImpostor: otherImpostor,
  82669. joint: joint
  82670. });
  82671. if (this._physicsEngine) {
  82672. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82673. }
  82674. return this;
  82675. };
  82676. /**
  82677. * Will keep this body still, in a sleep mode.
  82678. */
  82679. PhysicsImpostor.prototype.sleep = function () {
  82680. if (this._physicsEngine) {
  82681. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82682. }
  82683. return this;
  82684. };
  82685. /**
  82686. * Wake the body up.
  82687. */
  82688. PhysicsImpostor.prototype.wakeUp = function () {
  82689. if (this._physicsEngine) {
  82690. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82691. }
  82692. return this;
  82693. };
  82694. PhysicsImpostor.prototype.clone = function (newObject) {
  82695. if (!newObject)
  82696. return null;
  82697. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82698. };
  82699. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82700. var _this = this;
  82701. //no dispose if no physics engine is available.
  82702. if (!this._physicsEngine) {
  82703. return;
  82704. }
  82705. this._joints.forEach(function (j) {
  82706. if (_this._physicsEngine) {
  82707. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82708. }
  82709. });
  82710. //dispose the physics body
  82711. this._physicsEngine.removeImpostor(this);
  82712. if (this.parent) {
  82713. this.parent.forceUpdate();
  82714. }
  82715. else {
  82716. /*this._object.getChildMeshes().forEach(function(mesh) {
  82717. if (mesh.physicsImpostor) {
  82718. if (disposeChildren) {
  82719. mesh.physicsImpostor.dispose();
  82720. mesh.physicsImpostor = null;
  82721. }
  82722. }
  82723. })*/
  82724. }
  82725. this._isDisposed = true;
  82726. };
  82727. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82728. this._deltaPosition.copyFrom(position);
  82729. };
  82730. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82731. if (!this._deltaRotation) {
  82732. this._deltaRotation = new BABYLON.Quaternion();
  82733. }
  82734. this._deltaRotation.copyFrom(rotation);
  82735. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82736. };
  82737. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82738. if (this._physicsEngine) {
  82739. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82740. }
  82741. return this;
  82742. };
  82743. PhysicsImpostor.prototype.getRadius = function () {
  82744. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82745. };
  82746. /**
  82747. * Sync a bone with this impostor
  82748. * @param bone The bone to sync to the impostor.
  82749. * @param boneMesh The mesh that the bone is influencing.
  82750. * @param jointPivot The pivot of the joint / bone in local space.
  82751. * @param distToJoint Optional distance from the impostor to the joint.
  82752. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82753. */
  82754. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82755. var tempVec = PhysicsImpostor._tmpVecs[0];
  82756. var mesh = this.object;
  82757. if (mesh.rotationQuaternion) {
  82758. if (adjustRotation) {
  82759. var tempQuat = PhysicsImpostor._tmpQuat;
  82760. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82761. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82762. }
  82763. else {
  82764. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82765. }
  82766. }
  82767. tempVec.x = 0;
  82768. tempVec.y = 0;
  82769. tempVec.z = 0;
  82770. if (jointPivot) {
  82771. tempVec.x = jointPivot.x;
  82772. tempVec.y = jointPivot.y;
  82773. tempVec.z = jointPivot.z;
  82774. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82775. if (distToJoint === undefined || distToJoint === null) {
  82776. distToJoint = jointPivot.length();
  82777. }
  82778. tempVec.x *= distToJoint;
  82779. tempVec.y *= distToJoint;
  82780. tempVec.z *= distToJoint;
  82781. }
  82782. if (bone.getParent()) {
  82783. tempVec.addInPlace(mesh.getAbsolutePosition());
  82784. bone.setAbsolutePosition(tempVec, boneMesh);
  82785. }
  82786. else {
  82787. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82788. boneMesh.position.x -= tempVec.x;
  82789. boneMesh.position.y -= tempVec.y;
  82790. boneMesh.position.z -= tempVec.z;
  82791. }
  82792. };
  82793. /**
  82794. * Sync impostor to a bone
  82795. * @param bone The bone that the impostor will be synced to.
  82796. * @param boneMesh The mesh that the bone is influencing.
  82797. * @param jointPivot The pivot of the joint / bone in local space.
  82798. * @param distToJoint Optional distance from the impostor to the joint.
  82799. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82800. * @param boneAxis Optional vector3 axis the bone is aligned with
  82801. */
  82802. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82803. var mesh = this.object;
  82804. if (mesh.rotationQuaternion) {
  82805. if (adjustRotation) {
  82806. var tempQuat = PhysicsImpostor._tmpQuat;
  82807. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82808. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82809. }
  82810. else {
  82811. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82812. }
  82813. }
  82814. var pos = PhysicsImpostor._tmpVecs[0];
  82815. var boneDir = PhysicsImpostor._tmpVecs[1];
  82816. if (!boneAxis) {
  82817. boneAxis = PhysicsImpostor._tmpVecs[2];
  82818. boneAxis.x = 0;
  82819. boneAxis.y = 1;
  82820. boneAxis.z = 0;
  82821. }
  82822. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82823. bone.getAbsolutePositionToRef(boneMesh, pos);
  82824. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82825. distToJoint = jointPivot.length();
  82826. }
  82827. if (distToJoint !== undefined && distToJoint !== null) {
  82828. pos.x += boneDir.x * distToJoint;
  82829. pos.y += boneDir.y * distToJoint;
  82830. pos.z += boneDir.z * distToJoint;
  82831. }
  82832. mesh.setAbsolutePosition(pos);
  82833. };
  82834. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82835. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82836. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82837. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82838. //Impostor types
  82839. PhysicsImpostor.NoImpostor = 0;
  82840. PhysicsImpostor.SphereImpostor = 1;
  82841. PhysicsImpostor.BoxImpostor = 2;
  82842. PhysicsImpostor.PlaneImpostor = 3;
  82843. PhysicsImpostor.MeshImpostor = 4;
  82844. PhysicsImpostor.CylinderImpostor = 7;
  82845. PhysicsImpostor.ParticleImpostor = 8;
  82846. PhysicsImpostor.HeightmapImpostor = 9;
  82847. return PhysicsImpostor;
  82848. }());
  82849. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82850. })(BABYLON || (BABYLON = {}));
  82851. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82852. var BABYLON;
  82853. (function (BABYLON) {
  82854. var PhysicsEngine = /** @class */ (function () {
  82855. function PhysicsEngine(gravity, _physicsPlugin) {
  82856. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82857. this._physicsPlugin = _physicsPlugin;
  82858. //new methods and parameters
  82859. this._impostors = [];
  82860. this._joints = [];
  82861. if (!this._physicsPlugin.isSupported()) {
  82862. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82863. + "Please make sure it is included.");
  82864. }
  82865. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82866. this.setGravity(gravity);
  82867. this.setTimeStep();
  82868. }
  82869. PhysicsEngine.prototype.setGravity = function (gravity) {
  82870. this.gravity = gravity;
  82871. this._physicsPlugin.setGravity(this.gravity);
  82872. };
  82873. /**
  82874. * Set the time step of the physics engine.
  82875. * default is 1/60.
  82876. * To slow it down, enter 1/600 for example.
  82877. * To speed it up, 1/30
  82878. * @param {number} newTimeStep the new timestep to apply to this world.
  82879. */
  82880. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82881. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82882. this._physicsPlugin.setTimeStep(newTimeStep);
  82883. };
  82884. /**
  82885. * Get the time step of the physics engine.
  82886. */
  82887. PhysicsEngine.prototype.getTimeStep = function () {
  82888. return this._physicsPlugin.getTimeStep();
  82889. };
  82890. PhysicsEngine.prototype.dispose = function () {
  82891. this._impostors.forEach(function (impostor) {
  82892. impostor.dispose();
  82893. });
  82894. this._physicsPlugin.dispose();
  82895. };
  82896. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82897. return this._physicsPlugin.name;
  82898. };
  82899. /**
  82900. * Adding a new impostor for the impostor tracking.
  82901. * This will be done by the impostor itself.
  82902. * @param {PhysicsImpostor} impostor the impostor to add
  82903. */
  82904. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82905. impostor.uniqueId = this._impostors.push(impostor);
  82906. //if no parent, generate the body
  82907. if (!impostor.parent) {
  82908. this._physicsPlugin.generatePhysicsBody(impostor);
  82909. }
  82910. };
  82911. /**
  82912. * Remove an impostor from the engine.
  82913. * This impostor and its mesh will not longer be updated by the physics engine.
  82914. * @param {PhysicsImpostor} impostor the impostor to remove
  82915. */
  82916. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82917. var index = this._impostors.indexOf(impostor);
  82918. if (index > -1) {
  82919. var removed = this._impostors.splice(index, 1);
  82920. //Is it needed?
  82921. if (removed.length) {
  82922. //this will also remove it from the world.
  82923. removed[0].physicsBody = null;
  82924. }
  82925. }
  82926. };
  82927. /**
  82928. * Add a joint to the physics engine
  82929. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82930. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82931. * @param {PhysicsJoint} the joint that will connect both impostors.
  82932. */
  82933. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82934. var impostorJoint = {
  82935. mainImpostor: mainImpostor,
  82936. connectedImpostor: connectedImpostor,
  82937. joint: joint
  82938. };
  82939. joint.physicsPlugin = this._physicsPlugin;
  82940. this._joints.push(impostorJoint);
  82941. this._physicsPlugin.generateJoint(impostorJoint);
  82942. };
  82943. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82944. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82945. return (impostorJoint.connectedImpostor === connectedImpostor
  82946. && impostorJoint.joint === joint
  82947. && impostorJoint.mainImpostor === mainImpostor);
  82948. });
  82949. if (matchingJoints.length) {
  82950. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82951. //TODO remove it from the list as well
  82952. }
  82953. };
  82954. /**
  82955. * Called by the scene. no need to call it.
  82956. */
  82957. PhysicsEngine.prototype._step = function (delta) {
  82958. var _this = this;
  82959. //check if any mesh has no body / requires an update
  82960. this._impostors.forEach(function (impostor) {
  82961. if (impostor.isBodyInitRequired()) {
  82962. _this._physicsPlugin.generatePhysicsBody(impostor);
  82963. }
  82964. });
  82965. if (delta > 0.1) {
  82966. delta = 0.1;
  82967. }
  82968. else if (delta <= 0) {
  82969. delta = 1.0 / 60.0;
  82970. }
  82971. this._physicsPlugin.executeStep(delta, this._impostors);
  82972. };
  82973. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82974. return this._physicsPlugin;
  82975. };
  82976. PhysicsEngine.prototype.getImpostors = function () {
  82977. return this._impostors;
  82978. };
  82979. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82980. for (var i = 0; i < this._impostors.length; ++i) {
  82981. if (this._impostors[i].object === object) {
  82982. return this._impostors[i];
  82983. }
  82984. }
  82985. return null;
  82986. };
  82987. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82988. for (var i = 0; i < this._impostors.length; ++i) {
  82989. if (this._impostors[i].physicsBody === body) {
  82990. return this._impostors[i];
  82991. }
  82992. }
  82993. return null;
  82994. };
  82995. // Statics
  82996. PhysicsEngine.Epsilon = 0.001;
  82997. return PhysicsEngine;
  82998. }());
  82999. BABYLON.PhysicsEngine = PhysicsEngine;
  83000. })(BABYLON || (BABYLON = {}));
  83001. //# sourceMappingURL=babylon.physicsEngine.js.map
  83002. var BABYLON;
  83003. (function (BABYLON) {
  83004. var PhysicsHelper = /** @class */ (function () {
  83005. function PhysicsHelper(scene) {
  83006. this._scene = scene;
  83007. this._physicsEngine = this._scene.getPhysicsEngine();
  83008. if (!this._physicsEngine) {
  83009. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83010. }
  83011. }
  83012. /**
  83013. * @param {Vector3} origin the origin of the explosion
  83014. * @param {number} radius the explosion radius
  83015. * @param {number} strength the explosion strength
  83016. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83017. */
  83018. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83019. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83020. if (!this._physicsEngine) {
  83021. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83022. return null;
  83023. }
  83024. var impostors = this._physicsEngine.getImpostors();
  83025. if (impostors.length === 0) {
  83026. return null;
  83027. }
  83028. var event = new PhysicsRadialExplosionEvent(this._scene);
  83029. impostors.forEach(function (impostor) {
  83030. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83031. if (!impostorForceAndContactPoint) {
  83032. return;
  83033. }
  83034. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83035. });
  83036. event.dispose(false);
  83037. return event;
  83038. };
  83039. /**
  83040. * @param {Vector3} origin the origin of the explosion
  83041. * @param {number} radius the explosion radius
  83042. * @param {number} strength the explosion strength
  83043. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83044. */
  83045. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83046. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83047. if (!this._physicsEngine) {
  83048. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83049. return null;
  83050. }
  83051. var impostors = this._physicsEngine.getImpostors();
  83052. if (impostors.length === 0) {
  83053. return null;
  83054. }
  83055. var event = new PhysicsRadialExplosionEvent(this._scene);
  83056. impostors.forEach(function (impostor) {
  83057. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83058. if (!impostorForceAndContactPoint) {
  83059. return;
  83060. }
  83061. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83062. });
  83063. event.dispose(false);
  83064. return event;
  83065. };
  83066. /**
  83067. * @param {Vector3} origin the origin of the explosion
  83068. * @param {number} radius the explosion radius
  83069. * @param {number} strength the explosion strength
  83070. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83071. */
  83072. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83073. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83074. if (!this._physicsEngine) {
  83075. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83076. return null;
  83077. }
  83078. var impostors = this._physicsEngine.getImpostors();
  83079. if (impostors.length === 0) {
  83080. return null;
  83081. }
  83082. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83083. event.dispose(false);
  83084. return event;
  83085. };
  83086. /**
  83087. * @param {Vector3} origin the origin of the updraft
  83088. * @param {number} radius the radius of the updraft
  83089. * @param {number} strength the strength of the updraft
  83090. * @param {number} height the height of the updraft
  83091. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83092. */
  83093. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83094. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83095. if (!this._physicsEngine) {
  83096. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83097. return null;
  83098. }
  83099. if (this._physicsEngine.getImpostors().length === 0) {
  83100. return null;
  83101. }
  83102. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83103. event.dispose(false);
  83104. return event;
  83105. };
  83106. /**
  83107. * @param {Vector3} origin the of the vortex
  83108. * @param {number} radius the radius of the vortex
  83109. * @param {number} strength the strength of the vortex
  83110. * @param {number} height the height of the vortex
  83111. */
  83112. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83113. if (!this._physicsEngine) {
  83114. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83115. return null;
  83116. }
  83117. if (this._physicsEngine.getImpostors().length === 0) {
  83118. return null;
  83119. }
  83120. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83121. event.dispose(false);
  83122. return event;
  83123. };
  83124. return PhysicsHelper;
  83125. }());
  83126. BABYLON.PhysicsHelper = PhysicsHelper;
  83127. /***** Radial explosion *****/
  83128. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83129. function PhysicsRadialExplosionEvent(scene) {
  83130. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83131. this._rays = [];
  83132. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83133. this._scene = scene;
  83134. }
  83135. /**
  83136. * Returns the data related to the radial explosion event (sphere & rays).
  83137. * @returns {PhysicsRadialExplosionEventData}
  83138. */
  83139. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83140. this._dataFetched = true;
  83141. return {
  83142. sphere: this._sphere,
  83143. rays: this._rays,
  83144. };
  83145. };
  83146. /**
  83147. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83148. * @param impostor
  83149. * @param {Vector3} origin the origin of the explosion
  83150. * @param {number} radius the explosion radius
  83151. * @param {number} strength the explosion strength
  83152. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83153. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83154. */
  83155. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83156. if (impostor.mass === 0) {
  83157. return null;
  83158. }
  83159. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83160. return null;
  83161. }
  83162. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83163. return null;
  83164. }
  83165. var impostorObjectCenter = impostor.getObjectCenter();
  83166. var direction = impostorObjectCenter.subtract(origin);
  83167. var ray = new BABYLON.Ray(origin, direction, radius);
  83168. this._rays.push(ray);
  83169. var hit = ray.intersectsMesh(impostor.object);
  83170. var contactPoint = hit.pickedPoint;
  83171. if (!contactPoint) {
  83172. return null;
  83173. }
  83174. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83175. if (distanceFromOrigin > radius) {
  83176. return null;
  83177. }
  83178. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83179. ? strength
  83180. : strength * (1 - (distanceFromOrigin / radius));
  83181. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83182. return { force: force, contactPoint: contactPoint };
  83183. };
  83184. /**
  83185. * Disposes the sphere.
  83186. * @param {bolean} force
  83187. */
  83188. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83189. var _this = this;
  83190. if (force === void 0) { force = true; }
  83191. if (force) {
  83192. this._sphere.dispose();
  83193. }
  83194. else {
  83195. setTimeout(function () {
  83196. if (!_this._dataFetched) {
  83197. _this._sphere.dispose();
  83198. }
  83199. }, 0);
  83200. }
  83201. };
  83202. /*** Helpers ***/
  83203. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83204. if (!this._sphere) {
  83205. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83206. this._sphere.isVisible = false;
  83207. }
  83208. };
  83209. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83210. var impostorObject = impostor.object;
  83211. this._prepareSphere();
  83212. this._sphere.position = origin;
  83213. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83214. this._sphere._updateBoundingInfo();
  83215. this._sphere.computeWorldMatrix(true);
  83216. return this._sphere.intersectsMesh(impostorObject, true);
  83217. };
  83218. return PhysicsRadialExplosionEvent;
  83219. }());
  83220. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83221. /***** Gravitational Field *****/
  83222. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83223. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83224. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83225. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83226. this._physicsHelper = physicsHelper;
  83227. this._scene = scene;
  83228. this._origin = origin;
  83229. this._radius = radius;
  83230. this._strength = strength;
  83231. this._falloff = falloff;
  83232. this._tickCallback = this._tick.bind(this);
  83233. }
  83234. /**
  83235. * Returns the data related to the gravitational field event (sphere).
  83236. * @returns {PhysicsGravitationalFieldEventData}
  83237. */
  83238. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83239. this._dataFetched = true;
  83240. return {
  83241. sphere: this._sphere,
  83242. };
  83243. };
  83244. /**
  83245. * Enables the gravitational field.
  83246. */
  83247. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83248. this._tickCallback.call(this);
  83249. this._scene.registerBeforeRender(this._tickCallback);
  83250. };
  83251. /**
  83252. * Disables the gravitational field.
  83253. */
  83254. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83255. this._scene.unregisterBeforeRender(this._tickCallback);
  83256. };
  83257. /**
  83258. * Disposes the sphere.
  83259. * @param {bolean} force
  83260. */
  83261. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83262. var _this = this;
  83263. if (force === void 0) { force = true; }
  83264. if (force) {
  83265. this._sphere.dispose();
  83266. }
  83267. else {
  83268. setTimeout(function () {
  83269. if (!_this._dataFetched) {
  83270. _this._sphere.dispose();
  83271. }
  83272. }, 0);
  83273. }
  83274. };
  83275. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  83276. // Since the params won't change, we fetch the event only once
  83277. if (this._sphere) {
  83278. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83279. }
  83280. else {
  83281. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83282. if (radialExplosionEvent) {
  83283. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  83284. }
  83285. }
  83286. };
  83287. return PhysicsGravitationalFieldEvent;
  83288. }());
  83289. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83290. /***** Updraft *****/
  83291. var PhysicsUpdraftEvent = /** @class */ (function () {
  83292. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83293. this._scene = _scene;
  83294. this._origin = _origin;
  83295. this._radius = _radius;
  83296. this._strength = _strength;
  83297. this._height = _height;
  83298. this._updraftMode = _updraftMode;
  83299. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83300. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83301. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83302. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83303. this._physicsEngine = this._scene.getPhysicsEngine();
  83304. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83305. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83306. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83307. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83308. }
  83309. this._tickCallback = this._tick.bind(this);
  83310. }
  83311. /**
  83312. * Returns the data related to the updraft event (cylinder).
  83313. * @returns {PhysicsUpdraftEventData}
  83314. */
  83315. PhysicsUpdraftEvent.prototype.getData = function () {
  83316. this._dataFetched = true;
  83317. return {
  83318. cylinder: this._cylinder,
  83319. };
  83320. };
  83321. /**
  83322. * Enables the updraft.
  83323. */
  83324. PhysicsUpdraftEvent.prototype.enable = function () {
  83325. this._tickCallback.call(this);
  83326. this._scene.registerBeforeRender(this._tickCallback);
  83327. };
  83328. /**
  83329. * Disables the cortex.
  83330. */
  83331. PhysicsUpdraftEvent.prototype.disable = function () {
  83332. this._scene.unregisterBeforeRender(this._tickCallback);
  83333. };
  83334. /**
  83335. * Disposes the sphere.
  83336. * @param {bolean} force
  83337. */
  83338. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83339. var _this = this;
  83340. if (force === void 0) { force = true; }
  83341. if (force) {
  83342. this._cylinder.dispose();
  83343. }
  83344. else {
  83345. setTimeout(function () {
  83346. if (!_this._dataFetched) {
  83347. _this._cylinder.dispose();
  83348. }
  83349. }, 0);
  83350. }
  83351. };
  83352. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83353. if (impostor.mass === 0) {
  83354. return null;
  83355. }
  83356. if (!this._intersectsWithCylinder(impostor)) {
  83357. return null;
  83358. }
  83359. var impostorObjectCenter = impostor.getObjectCenter();
  83360. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83361. var direction = this._originDirection;
  83362. }
  83363. else {
  83364. var direction = impostorObjectCenter.subtract(this._originTop);
  83365. }
  83366. var multiplier = this._strength * -1;
  83367. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83368. return { force: force, contactPoint: impostorObjectCenter };
  83369. };
  83370. PhysicsUpdraftEvent.prototype._tick = function () {
  83371. var _this = this;
  83372. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83373. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83374. if (!impostorForceAndContactPoint) {
  83375. return;
  83376. }
  83377. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83378. });
  83379. };
  83380. /*** Helpers ***/
  83381. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83382. if (!this._cylinder) {
  83383. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83384. height: this._height,
  83385. diameter: this._radius * 2,
  83386. }, this._scene);
  83387. this._cylinder.isVisible = false;
  83388. }
  83389. };
  83390. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83391. var impostorObject = impostor.object;
  83392. this._prepareCylinder();
  83393. this._cylinder.position = this._cylinderPosition;
  83394. return this._cylinder.intersectsMesh(impostorObject, true);
  83395. };
  83396. return PhysicsUpdraftEvent;
  83397. }());
  83398. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83399. /***** Vortex *****/
  83400. var PhysicsVortexEvent = /** @class */ (function () {
  83401. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83402. this._scene = _scene;
  83403. this._origin = _origin;
  83404. this._radius = _radius;
  83405. this._strength = _strength;
  83406. this._height = _height;
  83407. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83408. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83409. this._updraftMultiplier = 0.02;
  83410. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83411. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83412. this._physicsEngine = this._scene.getPhysicsEngine();
  83413. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83414. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83415. this._tickCallback = this._tick.bind(this);
  83416. }
  83417. /**
  83418. * Returns the data related to the vortex event (cylinder).
  83419. * @returns {PhysicsVortexEventData}
  83420. */
  83421. PhysicsVortexEvent.prototype.getData = function () {
  83422. this._dataFetched = true;
  83423. return {
  83424. cylinder: this._cylinder,
  83425. };
  83426. };
  83427. /**
  83428. * Enables the vortex.
  83429. */
  83430. PhysicsVortexEvent.prototype.enable = function () {
  83431. this._tickCallback.call(this);
  83432. this._scene.registerBeforeRender(this._tickCallback);
  83433. };
  83434. /**
  83435. * Disables the cortex.
  83436. */
  83437. PhysicsVortexEvent.prototype.disable = function () {
  83438. this._scene.unregisterBeforeRender(this._tickCallback);
  83439. };
  83440. /**
  83441. * Disposes the sphere.
  83442. * @param {bolean} force
  83443. */
  83444. PhysicsVortexEvent.prototype.dispose = function (force) {
  83445. var _this = this;
  83446. if (force === void 0) { force = true; }
  83447. if (force) {
  83448. this._cylinder.dispose();
  83449. }
  83450. else {
  83451. setTimeout(function () {
  83452. if (!_this._dataFetched) {
  83453. _this._cylinder.dispose();
  83454. }
  83455. }, 0);
  83456. }
  83457. };
  83458. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83459. if (impostor.mass === 0) {
  83460. return null;
  83461. }
  83462. if (!this._intersectsWithCylinder(impostor)) {
  83463. return null;
  83464. }
  83465. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83466. return null;
  83467. }
  83468. var impostorObjectCenter = impostor.getObjectCenter();
  83469. 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)
  83470. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83471. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83472. var hit = ray.intersectsMesh(impostor.object);
  83473. var contactPoint = hit.pickedPoint;
  83474. if (!contactPoint) {
  83475. return null;
  83476. }
  83477. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83478. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83479. var directionToOrigin = contactPoint.normalize();
  83480. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83481. directionToOrigin = directionToOrigin.negate();
  83482. }
  83483. // TODO: find a more physically based solution
  83484. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83485. var forceX = directionToOrigin.x * this._strength / 8;
  83486. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83487. var forceZ = directionToOrigin.z * this._strength / 8;
  83488. }
  83489. else {
  83490. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83491. var forceY = this._originTop.y * this._updraftMultiplier;
  83492. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83493. }
  83494. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83495. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83496. return { force: force, contactPoint: impostorObjectCenter };
  83497. };
  83498. PhysicsVortexEvent.prototype._tick = function () {
  83499. var _this = this;
  83500. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83501. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83502. if (!impostorForceAndContactPoint) {
  83503. return;
  83504. }
  83505. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83506. });
  83507. };
  83508. /*** Helpers ***/
  83509. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83510. if (!this._cylinder) {
  83511. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83512. height: this._height,
  83513. diameter: this._radius * 2,
  83514. }, this._scene);
  83515. this._cylinder.isVisible = false;
  83516. }
  83517. };
  83518. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83519. var impostorObject = impostor.object;
  83520. this._prepareCylinder();
  83521. this._cylinder.position = this._cylinderPosition;
  83522. return this._cylinder.intersectsMesh(impostorObject, true);
  83523. };
  83524. return PhysicsVortexEvent;
  83525. }());
  83526. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83527. /***** Enums *****/
  83528. /**
  83529. * The strenght of the force in correspondence to the distance of the affected object
  83530. */
  83531. var PhysicsRadialImpulseFalloff;
  83532. (function (PhysicsRadialImpulseFalloff) {
  83533. /** Defines that impulse is constant in strength across it's whole radius */
  83534. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83535. /** DEfines that impulse gets weaker if it's further from the origin */
  83536. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83537. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83538. /**
  83539. * The strenght of the force in correspondence to the distance of the affected object
  83540. */
  83541. var PhysicsUpdraftMode;
  83542. (function (PhysicsUpdraftMode) {
  83543. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83544. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83545. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83546. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83547. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83548. })(BABYLON || (BABYLON = {}));
  83549. //# sourceMappingURL=babylon.physicsHelper.js.map
  83550. var BABYLON;
  83551. (function (BABYLON) {
  83552. var CannonJSPlugin = /** @class */ (function () {
  83553. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83554. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83555. if (iterations === void 0) { iterations = 10; }
  83556. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83557. this.name = "CannonJSPlugin";
  83558. this._physicsMaterials = new Array();
  83559. this._fixedTimeStep = 1 / 60;
  83560. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83561. this.BJSCANNON = CANNON;
  83562. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83563. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83564. this._tmpPosition = BABYLON.Vector3.Zero();
  83565. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83566. this._tmpUnityRotation = new BABYLON.Quaternion();
  83567. if (!this.isSupported()) {
  83568. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83569. return;
  83570. }
  83571. this._extendNamespace();
  83572. this.world = new this.BJSCANNON.World();
  83573. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83574. this.world.solver.iterations = iterations;
  83575. }
  83576. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83577. this.world.gravity.copy(gravity);
  83578. };
  83579. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83580. this._fixedTimeStep = timeStep;
  83581. };
  83582. CannonJSPlugin.prototype.getTimeStep = function () {
  83583. return this._fixedTimeStep;
  83584. };
  83585. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83586. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83587. };
  83588. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83589. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83590. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83591. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83592. };
  83593. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83594. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83595. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83596. impostor.physicsBody.applyForce(impulse, worldPoint);
  83597. };
  83598. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83599. //parent-child relationship. Does this impostor has a parent impostor?
  83600. if (impostor.parent) {
  83601. if (impostor.physicsBody) {
  83602. this.removePhysicsBody(impostor);
  83603. //TODO is that needed?
  83604. impostor.forceUpdate();
  83605. }
  83606. return;
  83607. }
  83608. //should a new body be created for this impostor?
  83609. if (impostor.isBodyInitRequired()) {
  83610. var shape = this._createShape(impostor);
  83611. //unregister events, if body is being changed
  83612. var oldBody = impostor.physicsBody;
  83613. if (oldBody) {
  83614. this.removePhysicsBody(impostor);
  83615. }
  83616. //create the body and material
  83617. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83618. var bodyCreationObject = {
  83619. mass: impostor.getParam("mass"),
  83620. material: material
  83621. };
  83622. // A simple extend, in case native options were used.
  83623. var nativeOptions = impostor.getParam("nativeOptions");
  83624. for (var key in nativeOptions) {
  83625. if (nativeOptions.hasOwnProperty(key)) {
  83626. bodyCreationObject[key] = nativeOptions[key];
  83627. }
  83628. }
  83629. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83630. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83631. this.world.addEventListener("preStep", impostor.beforeStep);
  83632. this.world.addEventListener("postStep", impostor.afterStep);
  83633. impostor.physicsBody.addShape(shape);
  83634. this.world.add(impostor.physicsBody);
  83635. //try to keep the body moving in the right direction by taking old properties.
  83636. //Should be tested!
  83637. if (oldBody) {
  83638. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83639. impostor.physicsBody[param].copy(oldBody[param]);
  83640. });
  83641. }
  83642. this._processChildMeshes(impostor);
  83643. }
  83644. //now update the body's transformation
  83645. this._updatePhysicsBodyTransformation(impostor);
  83646. };
  83647. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83648. var _this = this;
  83649. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83650. var currentRotation = mainImpostor.object.rotationQuaternion;
  83651. if (meshChildren.length) {
  83652. var processMesh = function (localPosition, mesh) {
  83653. if (!currentRotation || !mesh.rotationQuaternion) {
  83654. return;
  83655. }
  83656. var childImpostor = mesh.getPhysicsImpostor();
  83657. if (childImpostor) {
  83658. var parent = childImpostor.parent;
  83659. if (parent !== mainImpostor) {
  83660. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83661. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83662. if (childImpostor.physicsBody) {
  83663. _this.removePhysicsBody(childImpostor);
  83664. childImpostor.physicsBody = null;
  83665. }
  83666. childImpostor.parent = mainImpostor;
  83667. childImpostor.resetUpdateFlags();
  83668. 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));
  83669. //Add the mass of the children.
  83670. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83671. }
  83672. }
  83673. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83674. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83675. };
  83676. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83677. }
  83678. };
  83679. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83680. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83681. this.world.removeEventListener("preStep", impostor.beforeStep);
  83682. this.world.removeEventListener("postStep", impostor.afterStep);
  83683. this.world.remove(impostor.physicsBody);
  83684. };
  83685. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83686. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83687. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83688. if (!mainBody || !connectedBody) {
  83689. return;
  83690. }
  83691. var constraint;
  83692. var jointData = impostorJoint.joint.jointData;
  83693. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83694. var constraintData = {
  83695. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83696. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83697. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83698. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83699. maxForce: jointData.nativeParams.maxForce,
  83700. collideConnected: !!jointData.collision
  83701. };
  83702. switch (impostorJoint.joint.type) {
  83703. case BABYLON.PhysicsJoint.HingeJoint:
  83704. case BABYLON.PhysicsJoint.Hinge2Joint:
  83705. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83706. break;
  83707. case BABYLON.PhysicsJoint.DistanceJoint:
  83708. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83709. break;
  83710. case BABYLON.PhysicsJoint.SpringJoint:
  83711. var springData = jointData;
  83712. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83713. restLength: springData.length,
  83714. stiffness: springData.stiffness,
  83715. damping: springData.damping,
  83716. localAnchorA: constraintData.pivotA,
  83717. localAnchorB: constraintData.pivotB
  83718. });
  83719. break;
  83720. case BABYLON.PhysicsJoint.LockJoint:
  83721. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83722. break;
  83723. case BABYLON.PhysicsJoint.PointToPointJoint:
  83724. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83725. default:
  83726. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83727. break;
  83728. }
  83729. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83730. constraint.collideConnected = !!jointData.collision;
  83731. impostorJoint.joint.physicsJoint = constraint;
  83732. //don't add spring as constraint, as it is not one.
  83733. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83734. this.world.addConstraint(constraint);
  83735. }
  83736. else {
  83737. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83738. constraint.applyForce();
  83739. });
  83740. }
  83741. };
  83742. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83743. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83744. };
  83745. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83746. var index;
  83747. var mat;
  83748. for (index = 0; index < this._physicsMaterials.length; index++) {
  83749. mat = this._physicsMaterials[index];
  83750. if (mat.friction === friction && mat.restitution === restitution) {
  83751. return mat;
  83752. }
  83753. }
  83754. var currentMat = new this.BJSCANNON.Material(name);
  83755. currentMat.friction = friction;
  83756. currentMat.restitution = restitution;
  83757. this._physicsMaterials.push(currentMat);
  83758. return currentMat;
  83759. };
  83760. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83761. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83762. };
  83763. CannonJSPlugin.prototype._createShape = function (impostor) {
  83764. var object = impostor.object;
  83765. var returnValue;
  83766. var extendSize = impostor.getObjectExtendSize();
  83767. switch (impostor.type) {
  83768. case BABYLON.PhysicsImpostor.SphereImpostor:
  83769. var radiusX = extendSize.x;
  83770. var radiusY = extendSize.y;
  83771. var radiusZ = extendSize.z;
  83772. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83773. break;
  83774. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83775. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83776. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83777. break;
  83778. case BABYLON.PhysicsImpostor.BoxImpostor:
  83779. var box = extendSize.scale(0.5);
  83780. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83781. break;
  83782. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83783. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83784. returnValue = new this.BJSCANNON.Plane();
  83785. break;
  83786. case BABYLON.PhysicsImpostor.MeshImpostor:
  83787. // should transform the vertex data to world coordinates!!
  83788. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83789. var rawFaces = object.getIndices ? object.getIndices() : [];
  83790. if (!rawVerts)
  83791. return;
  83792. // get only scale! so the object could transform correctly.
  83793. var oldPosition = object.position.clone();
  83794. var oldRotation = object.rotation && object.rotation.clone();
  83795. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83796. object.position.copyFromFloats(0, 0, 0);
  83797. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83798. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83799. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83800. var transform = object.computeWorldMatrix(true);
  83801. // convert rawVerts to object space
  83802. var temp = new Array();
  83803. var index;
  83804. for (index = 0; index < rawVerts.length; index += 3) {
  83805. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83806. }
  83807. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83808. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83809. //now set back the transformation!
  83810. object.position.copyFrom(oldPosition);
  83811. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83812. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83813. break;
  83814. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83815. var oldPosition2 = object.position.clone();
  83816. var oldRotation2 = object.rotation && object.rotation.clone();
  83817. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83818. object.position.copyFromFloats(0, 0, 0);
  83819. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83820. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83821. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83822. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83823. returnValue = this._createHeightmap(object);
  83824. object.position.copyFrom(oldPosition2);
  83825. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83826. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83827. object.computeWorldMatrix(true);
  83828. break;
  83829. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83830. returnValue = new this.BJSCANNON.Particle();
  83831. break;
  83832. }
  83833. return returnValue;
  83834. };
  83835. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83836. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83837. var transform = object.computeWorldMatrix(true);
  83838. // convert rawVerts to object space
  83839. var temp = new Array();
  83840. var index;
  83841. for (index = 0; index < pos.length; index += 3) {
  83842. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83843. }
  83844. pos = temp;
  83845. var matrix = new Array();
  83846. //For now pointDepth will not be used and will be automatically calculated.
  83847. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83848. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83849. var boundingInfo = object.getBoundingInfo();
  83850. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83851. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83852. var elementSize = dim * 2 / arraySize;
  83853. for (var i = 0; i < pos.length; i = i + 3) {
  83854. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83855. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83856. var y = -pos[i + 2] + minY;
  83857. if (!matrix[x]) {
  83858. matrix[x] = [];
  83859. }
  83860. if (!matrix[x][z]) {
  83861. matrix[x][z] = y;
  83862. }
  83863. matrix[x][z] = Math.max(y, matrix[x][z]);
  83864. }
  83865. for (var x = 0; x <= arraySize; ++x) {
  83866. if (!matrix[x]) {
  83867. var loc = 1;
  83868. while (!matrix[(x + loc) % arraySize]) {
  83869. loc++;
  83870. }
  83871. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83872. //console.log("missing x", x);
  83873. }
  83874. for (var z = 0; z <= arraySize; ++z) {
  83875. if (!matrix[x][z]) {
  83876. var loc = 1;
  83877. var newValue;
  83878. while (newValue === undefined) {
  83879. newValue = matrix[x][(z + loc++) % arraySize];
  83880. }
  83881. matrix[x][z] = newValue;
  83882. }
  83883. }
  83884. }
  83885. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83886. elementSize: elementSize
  83887. });
  83888. //For future reference, needed for body transformation
  83889. shape.minY = minY;
  83890. return shape;
  83891. };
  83892. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83893. var object = impostor.object;
  83894. //make sure it is updated...
  83895. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83896. // The delta between the mesh position and the mesh bounding box center
  83897. var bInfo = object.getBoundingInfo();
  83898. if (!bInfo)
  83899. return;
  83900. var center = impostor.getObjectCenter();
  83901. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83902. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83903. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83904. this._tmpPosition.copyFrom(center);
  83905. var quaternion = object.rotationQuaternion;
  83906. if (!quaternion) {
  83907. return;
  83908. }
  83909. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83910. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83911. //-90 DEG in X, precalculated
  83912. quaternion = quaternion.multiply(this._minus90X);
  83913. //Invert! (Precalculated, 90 deg in X)
  83914. //No need to clone. this will never change.
  83915. impostor.setDeltaRotation(this._plus90X);
  83916. }
  83917. //If it is a heightfield, if should be centered.
  83918. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83919. var mesh = object;
  83920. var boundingInfo = mesh.getBoundingInfo();
  83921. //calculate the correct body position:
  83922. var rotationQuaternion = mesh.rotationQuaternion;
  83923. mesh.rotationQuaternion = this._tmpUnityRotation;
  83924. mesh.computeWorldMatrix(true);
  83925. //get original center with no rotation
  83926. var c = center.clone();
  83927. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83928. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83929. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83930. mesh.setPreTransformMatrix(p);
  83931. mesh.computeWorldMatrix(true);
  83932. //calculate the translation
  83933. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83934. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83935. //add it inverted to the delta
  83936. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83937. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83938. //rotation is back
  83939. mesh.rotationQuaternion = rotationQuaternion;
  83940. mesh.setPreTransformMatrix(oldPivot);
  83941. mesh.computeWorldMatrix(true);
  83942. }
  83943. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83944. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83945. //this._tmpPosition.copyFrom(object.position);
  83946. }
  83947. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83948. //Now update the impostor object
  83949. impostor.physicsBody.position.copy(this._tmpPosition);
  83950. impostor.physicsBody.quaternion.copy(quaternion);
  83951. };
  83952. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83953. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83954. if (impostor.object.rotationQuaternion) {
  83955. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83956. }
  83957. };
  83958. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83959. impostor.physicsBody.position.copy(newPosition);
  83960. impostor.physicsBody.quaternion.copy(newRotation);
  83961. };
  83962. CannonJSPlugin.prototype.isSupported = function () {
  83963. return this.BJSCANNON !== undefined;
  83964. };
  83965. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83966. impostor.physicsBody.velocity.copy(velocity);
  83967. };
  83968. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83969. impostor.physicsBody.angularVelocity.copy(velocity);
  83970. };
  83971. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83972. var v = impostor.physicsBody.velocity;
  83973. if (!v) {
  83974. return null;
  83975. }
  83976. return new BABYLON.Vector3(v.x, v.y, v.z);
  83977. };
  83978. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83979. var v = impostor.physicsBody.angularVelocity;
  83980. if (!v) {
  83981. return null;
  83982. }
  83983. return new BABYLON.Vector3(v.x, v.y, v.z);
  83984. };
  83985. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83986. impostor.physicsBody.mass = mass;
  83987. impostor.physicsBody.updateMassProperties();
  83988. };
  83989. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83990. return impostor.physicsBody.mass;
  83991. };
  83992. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83993. return impostor.physicsBody.material.friction;
  83994. };
  83995. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83996. impostor.physicsBody.material.friction = friction;
  83997. };
  83998. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83999. return impostor.physicsBody.material.restitution;
  84000. };
  84001. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84002. impostor.physicsBody.material.restitution = restitution;
  84003. };
  84004. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84005. impostor.physicsBody.sleep();
  84006. };
  84007. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84008. impostor.physicsBody.wakeUp();
  84009. };
  84010. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84011. joint.physicsJoint.distance = maxDistance;
  84012. };
  84013. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84014. // if (!motorIndex) {
  84015. // joint.physicsJoint.enableMotor();
  84016. // }
  84017. // }
  84018. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84019. // if (!motorIndex) {
  84020. // joint.physicsJoint.disableMotor();
  84021. // }
  84022. // }
  84023. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84024. if (!motorIndex) {
  84025. joint.physicsJoint.enableMotor();
  84026. joint.physicsJoint.setMotorSpeed(speed);
  84027. if (maxForce) {
  84028. this.setLimit(joint, maxForce);
  84029. }
  84030. }
  84031. };
  84032. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84033. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84034. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84035. };
  84036. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84037. var body = impostor.physicsBody;
  84038. mesh.position.x = body.position.x;
  84039. mesh.position.y = body.position.y;
  84040. mesh.position.z = body.position.z;
  84041. if (mesh.rotationQuaternion) {
  84042. mesh.rotationQuaternion.x = body.quaternion.x;
  84043. mesh.rotationQuaternion.y = body.quaternion.y;
  84044. mesh.rotationQuaternion.z = body.quaternion.z;
  84045. mesh.rotationQuaternion.w = body.quaternion.w;
  84046. }
  84047. };
  84048. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84049. var shape = impostor.physicsBody.shapes[0];
  84050. return shape.boundingSphereRadius;
  84051. };
  84052. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84053. var shape = impostor.physicsBody.shapes[0];
  84054. result.x = shape.halfExtents.x * 2;
  84055. result.y = shape.halfExtents.y * 2;
  84056. result.z = shape.halfExtents.z * 2;
  84057. };
  84058. CannonJSPlugin.prototype.dispose = function () {
  84059. };
  84060. CannonJSPlugin.prototype._extendNamespace = function () {
  84061. //this will force cannon to execute at least one step when using interpolation
  84062. var step_tmp1 = new this.BJSCANNON.Vec3();
  84063. var Engine = this.BJSCANNON;
  84064. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84065. maxSubSteps = maxSubSteps || 10;
  84066. timeSinceLastCalled = timeSinceLastCalled || 0;
  84067. if (timeSinceLastCalled === 0) {
  84068. this.internalStep(dt);
  84069. this.time += dt;
  84070. }
  84071. else {
  84072. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84073. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84074. var t0 = performance.now();
  84075. for (var i = 0; i !== internalSteps; i++) {
  84076. this.internalStep(dt);
  84077. if (performance.now() - t0 > dt * 1000) {
  84078. break;
  84079. }
  84080. }
  84081. this.time += timeSinceLastCalled;
  84082. var h = this.time % dt;
  84083. var h_div_dt = h / dt;
  84084. var interpvelo = step_tmp1;
  84085. var bodies = this.bodies;
  84086. for (var j = 0; j !== bodies.length; j++) {
  84087. var b = bodies[j];
  84088. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84089. b.position.vsub(b.previousPosition, interpvelo);
  84090. interpvelo.scale(h_div_dt, interpvelo);
  84091. b.position.vadd(interpvelo, b.interpolatedPosition);
  84092. }
  84093. else {
  84094. b.interpolatedPosition.copy(b.position);
  84095. b.interpolatedQuaternion.copy(b.quaternion);
  84096. }
  84097. }
  84098. }
  84099. };
  84100. };
  84101. return CannonJSPlugin;
  84102. }());
  84103. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84104. })(BABYLON || (BABYLON = {}));
  84105. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84106. var BABYLON;
  84107. (function (BABYLON) {
  84108. var OimoJSPlugin = /** @class */ (function () {
  84109. function OimoJSPlugin(iterations) {
  84110. this.name = "OimoJSPlugin";
  84111. this._tmpImpostorsArray = [];
  84112. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84113. this.BJSOIMO = OIMO;
  84114. this.world = new this.BJSOIMO.World({
  84115. iterations: iterations
  84116. });
  84117. this.world.clear();
  84118. }
  84119. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84120. this.world.gravity.copy(gravity);
  84121. };
  84122. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84123. this.world.timeStep = timeStep;
  84124. };
  84125. OimoJSPlugin.prototype.getTimeStep = function () {
  84126. return this.world.timeStep;
  84127. };
  84128. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84129. var _this = this;
  84130. impostors.forEach(function (impostor) {
  84131. impostor.beforeStep();
  84132. });
  84133. this.world.step();
  84134. impostors.forEach(function (impostor) {
  84135. impostor.afterStep();
  84136. //update the ordered impostors array
  84137. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84138. });
  84139. //check for collisions
  84140. var contact = this.world.contacts;
  84141. while (contact !== null) {
  84142. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84143. contact = contact.next;
  84144. continue;
  84145. }
  84146. //is this body colliding with any other? get the impostor
  84147. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84148. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84149. if (!mainImpostor || !collidingImpostor) {
  84150. contact = contact.next;
  84151. continue;
  84152. }
  84153. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84154. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84155. contact = contact.next;
  84156. }
  84157. };
  84158. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84159. var mass = impostor.physicsBody.mass;
  84160. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84161. };
  84162. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84163. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84164. this.applyImpulse(impostor, force, contactPoint);
  84165. };
  84166. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84167. var _this = this;
  84168. //parent-child relationship. Does this impostor has a parent impostor?
  84169. if (impostor.parent) {
  84170. if (impostor.physicsBody) {
  84171. this.removePhysicsBody(impostor);
  84172. //TODO is that needed?
  84173. impostor.forceUpdate();
  84174. }
  84175. return;
  84176. }
  84177. if (impostor.isBodyInitRequired()) {
  84178. var bodyConfig = {
  84179. name: impostor.uniqueId,
  84180. //Oimo must have mass, also for static objects.
  84181. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84182. size: [],
  84183. type: [],
  84184. pos: [],
  84185. posShape: [],
  84186. rot: [],
  84187. rotShape: [],
  84188. move: impostor.getParam("mass") !== 0,
  84189. density: impostor.getParam("mass"),
  84190. friction: impostor.getParam("friction"),
  84191. restitution: impostor.getParam("restitution"),
  84192. //Supporting older versions of Oimo
  84193. world: this.world
  84194. };
  84195. var impostors = [impostor];
  84196. var addToArray = function (parent) {
  84197. if (!parent.getChildMeshes)
  84198. return;
  84199. parent.getChildMeshes().forEach(function (m) {
  84200. if (m.physicsImpostor) {
  84201. impostors.push(m.physicsImpostor);
  84202. //m.physicsImpostor._init();
  84203. }
  84204. });
  84205. };
  84206. addToArray(impostor.object);
  84207. var checkWithEpsilon_1 = function (value) {
  84208. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84209. };
  84210. impostors.forEach(function (i) {
  84211. if (!i.object.rotationQuaternion) {
  84212. return;
  84213. }
  84214. //get the correct bounding box
  84215. var oldQuaternion = i.object.rotationQuaternion;
  84216. var rot = oldQuaternion.toEulerAngles();
  84217. var extendSize = i.getObjectExtendSize();
  84218. var radToDeg = 57.295779513082320876;
  84219. if (i === impostor) {
  84220. var center = impostor.getObjectCenter();
  84221. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84222. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84223. //Can also use Array.prototype.push.apply
  84224. bodyConfig.pos.push(center.x);
  84225. bodyConfig.pos.push(center.y);
  84226. bodyConfig.pos.push(center.z);
  84227. bodyConfig.posShape.push(0, 0, 0);
  84228. //tmp solution
  84229. bodyConfig.rot.push(rot.x * radToDeg);
  84230. bodyConfig.rot.push(rot.y * radToDeg);
  84231. bodyConfig.rot.push(rot.z * radToDeg);
  84232. bodyConfig.rotShape.push(0, 0, 0);
  84233. }
  84234. else {
  84235. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84236. bodyConfig.posShape.push(localPosition.x);
  84237. bodyConfig.posShape.push(localPosition.y);
  84238. bodyConfig.posShape.push(localPosition.z);
  84239. bodyConfig.pos.push(0, 0, 0);
  84240. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84241. bodyConfig.rot.push(0);
  84242. bodyConfig.rot.push(0);
  84243. bodyConfig.rot.push(0);
  84244. bodyConfig.rotShape.push(rot.x * radToDeg);
  84245. bodyConfig.rotShape.push(rot.y * radToDeg);
  84246. bodyConfig.rotShape.push(rot.z * radToDeg);
  84247. }
  84248. // register mesh
  84249. switch (i.type) {
  84250. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84251. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84252. case BABYLON.PhysicsImpostor.SphereImpostor:
  84253. var radiusX = extendSize.x;
  84254. var radiusY = extendSize.y;
  84255. var radiusZ = extendSize.z;
  84256. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84257. bodyConfig.type.push('sphere');
  84258. //due to the way oimo works with compounds, add 3 times
  84259. bodyConfig.size.push(size);
  84260. bodyConfig.size.push(size);
  84261. bodyConfig.size.push(size);
  84262. break;
  84263. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84264. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84265. var sizeY = checkWithEpsilon_1(extendSize.y);
  84266. bodyConfig.type.push('cylinder');
  84267. bodyConfig.size.push(sizeX);
  84268. bodyConfig.size.push(sizeY);
  84269. //due to the way oimo works with compounds, add one more value.
  84270. bodyConfig.size.push(sizeY);
  84271. break;
  84272. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84273. case BABYLON.PhysicsImpostor.BoxImpostor:
  84274. default:
  84275. var sizeX = checkWithEpsilon_1(extendSize.x);
  84276. var sizeY = checkWithEpsilon_1(extendSize.y);
  84277. var sizeZ = checkWithEpsilon_1(extendSize.z);
  84278. bodyConfig.type.push('box');
  84279. //if (i === impostor) {
  84280. bodyConfig.size.push(sizeX);
  84281. bodyConfig.size.push(sizeY);
  84282. bodyConfig.size.push(sizeZ);
  84283. //} else {
  84284. // bodyConfig.size.push(0,0,0);
  84285. //}
  84286. break;
  84287. }
  84288. //actually not needed, but hey...
  84289. i.object.rotationQuaternion = oldQuaternion;
  84290. });
  84291. impostor.physicsBody = this.world.add(bodyConfig);
  84292. }
  84293. else {
  84294. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84295. }
  84296. impostor.setDeltaPosition(this._tmpPositionVector);
  84297. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84298. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84299. };
  84300. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84301. //impostor.physicsBody.dispose();
  84302. //Same as : (older oimo versions)
  84303. this.world.removeRigidBody(impostor.physicsBody);
  84304. };
  84305. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84306. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84307. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84308. if (!mainBody || !connectedBody) {
  84309. return;
  84310. }
  84311. var jointData = impostorJoint.joint.jointData;
  84312. var options = jointData.nativeParams || {};
  84313. var type;
  84314. var nativeJointData = {
  84315. body1: mainBody,
  84316. body2: connectedBody,
  84317. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84318. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84319. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84320. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84321. min: options.min,
  84322. max: options.max,
  84323. collision: options.collision || jointData.collision,
  84324. spring: options.spring,
  84325. //supporting older version of Oimo
  84326. world: this.world
  84327. };
  84328. switch (impostorJoint.joint.type) {
  84329. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84330. type = "jointBall";
  84331. break;
  84332. case BABYLON.PhysicsJoint.SpringJoint:
  84333. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84334. var springData = jointData;
  84335. nativeJointData.min = springData.length || nativeJointData.min;
  84336. //Max should also be set, just make sure it is at least min
  84337. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84338. case BABYLON.PhysicsJoint.DistanceJoint:
  84339. type = "jointDistance";
  84340. nativeJointData.max = jointData.maxDistance;
  84341. break;
  84342. case BABYLON.PhysicsJoint.PrismaticJoint:
  84343. type = "jointPrisme";
  84344. break;
  84345. case BABYLON.PhysicsJoint.SliderJoint:
  84346. type = "jointSlide";
  84347. break;
  84348. case BABYLON.PhysicsJoint.WheelJoint:
  84349. type = "jointWheel";
  84350. break;
  84351. case BABYLON.PhysicsJoint.HingeJoint:
  84352. default:
  84353. type = "jointHinge";
  84354. break;
  84355. }
  84356. nativeJointData.type = type;
  84357. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84358. };
  84359. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84360. //Bug in Oimo prevents us from disposing a joint in the playground
  84361. //joint.joint.physicsJoint.dispose();
  84362. //So we will bruteforce it!
  84363. try {
  84364. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84365. }
  84366. catch (e) {
  84367. BABYLON.Tools.Warn(e);
  84368. }
  84369. };
  84370. OimoJSPlugin.prototype.isSupported = function () {
  84371. return this.BJSOIMO !== undefined;
  84372. };
  84373. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84374. if (!impostor.physicsBody.sleeping) {
  84375. //TODO check that
  84376. /*if (impostor.physicsBody.shapes.next) {
  84377. var parentShape = this._getLastShape(impostor.physicsBody);
  84378. impostor.object.position.copyFrom(parentShape.position);
  84379. console.log(parentShape.position);
  84380. } else {*/
  84381. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84382. //}
  84383. if (impostor.object.rotationQuaternion) {
  84384. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84385. }
  84386. }
  84387. };
  84388. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84389. var body = impostor.physicsBody;
  84390. body.position.copy(newPosition);
  84391. body.orientation.copy(newRotation);
  84392. body.syncShapes();
  84393. body.awake();
  84394. };
  84395. /*private _getLastShape(body: any): any {
  84396. var lastShape = body.shapes;
  84397. while (lastShape.next) {
  84398. lastShape = lastShape.next;
  84399. }
  84400. return lastShape;
  84401. }*/
  84402. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84403. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84404. };
  84405. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84406. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84407. };
  84408. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84409. var v = impostor.physicsBody.linearVelocity;
  84410. if (!v) {
  84411. return null;
  84412. }
  84413. return new BABYLON.Vector3(v.x, v.y, v.z);
  84414. };
  84415. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84416. var v = impostor.physicsBody.angularVelocity;
  84417. if (!v) {
  84418. return null;
  84419. }
  84420. return new BABYLON.Vector3(v.x, v.y, v.z);
  84421. };
  84422. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84423. var staticBody = mass === 0;
  84424. //this will actually set the body's density and not its mass.
  84425. //But this is how oimo treats the mass variable.
  84426. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84427. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84428. };
  84429. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84430. return impostor.physicsBody.shapes.density;
  84431. };
  84432. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84433. return impostor.physicsBody.shapes.friction;
  84434. };
  84435. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84436. impostor.physicsBody.shapes.friction = friction;
  84437. };
  84438. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84439. return impostor.physicsBody.shapes.restitution;
  84440. };
  84441. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84442. impostor.physicsBody.shapes.restitution = restitution;
  84443. };
  84444. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84445. impostor.physicsBody.sleep();
  84446. };
  84447. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84448. impostor.physicsBody.awake();
  84449. };
  84450. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84451. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84452. if (minDistance !== void 0) {
  84453. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84454. }
  84455. };
  84456. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84457. //TODO separate rotational and transational motors.
  84458. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84459. if (motor) {
  84460. motor.setMotor(speed, maxForce);
  84461. }
  84462. };
  84463. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84464. //TODO separate rotational and transational motors.
  84465. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84466. if (motor) {
  84467. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84468. }
  84469. };
  84470. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84471. var body = impostor.physicsBody;
  84472. mesh.position.x = body.position.x;
  84473. mesh.position.y = body.position.y;
  84474. mesh.position.z = body.position.z;
  84475. if (mesh.rotationQuaternion) {
  84476. mesh.rotationQuaternion.x = body.orientation.x;
  84477. mesh.rotationQuaternion.y = body.orientation.y;
  84478. mesh.rotationQuaternion.z = body.orientation.z;
  84479. mesh.rotationQuaternion.w = body.orientation.s;
  84480. }
  84481. };
  84482. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84483. return impostor.physicsBody.shapes.radius;
  84484. };
  84485. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84486. var shape = impostor.physicsBody.shapes;
  84487. result.x = shape.halfWidth * 2;
  84488. result.y = shape.halfHeight * 2;
  84489. result.z = shape.halfDepth * 2;
  84490. };
  84491. OimoJSPlugin.prototype.dispose = function () {
  84492. this.world.clear();
  84493. };
  84494. return OimoJSPlugin;
  84495. }());
  84496. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84497. })(BABYLON || (BABYLON = {}));
  84498. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84499. var BABYLON;
  84500. (function (BABYLON) {
  84501. /*
  84502. * Based on jsTGALoader - Javascript loader for TGA file
  84503. * By Vincent Thibault
  84504. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84505. */
  84506. var TGATools = /** @class */ (function () {
  84507. function TGATools() {
  84508. }
  84509. TGATools.GetTGAHeader = function (data) {
  84510. var offset = 0;
  84511. var header = {
  84512. id_length: data[offset++],
  84513. colormap_type: data[offset++],
  84514. image_type: data[offset++],
  84515. colormap_index: data[offset++] | data[offset++] << 8,
  84516. colormap_length: data[offset++] | data[offset++] << 8,
  84517. colormap_size: data[offset++],
  84518. origin: [
  84519. data[offset++] | data[offset++] << 8,
  84520. data[offset++] | data[offset++] << 8
  84521. ],
  84522. width: data[offset++] | data[offset++] << 8,
  84523. height: data[offset++] | data[offset++] << 8,
  84524. pixel_size: data[offset++],
  84525. flags: data[offset++]
  84526. };
  84527. return header;
  84528. };
  84529. TGATools.UploadContent = function (gl, data) {
  84530. // Not enough data to contain header ?
  84531. if (data.length < 19) {
  84532. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84533. return;
  84534. }
  84535. // Read Header
  84536. var offset = 18;
  84537. var header = TGATools.GetTGAHeader(data);
  84538. // Assume it's a valid Targa file.
  84539. if (header.id_length + offset > data.length) {
  84540. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84541. return;
  84542. }
  84543. // Skip not needed data
  84544. offset += header.id_length;
  84545. var use_rle = false;
  84546. var use_pal = false;
  84547. var use_grey = false;
  84548. // Get some informations.
  84549. switch (header.image_type) {
  84550. case TGATools._TYPE_RLE_INDEXED:
  84551. use_rle = true;
  84552. case TGATools._TYPE_INDEXED:
  84553. use_pal = true;
  84554. break;
  84555. case TGATools._TYPE_RLE_RGB:
  84556. use_rle = true;
  84557. case TGATools._TYPE_RGB:
  84558. // use_rgb = true;
  84559. break;
  84560. case TGATools._TYPE_RLE_GREY:
  84561. use_rle = true;
  84562. case TGATools._TYPE_GREY:
  84563. use_grey = true;
  84564. break;
  84565. }
  84566. var pixel_data;
  84567. // var numAlphaBits = header.flags & 0xf;
  84568. var pixel_size = header.pixel_size >> 3;
  84569. var pixel_total = header.width * header.height * pixel_size;
  84570. // Read palettes
  84571. var palettes;
  84572. if (use_pal) {
  84573. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84574. }
  84575. // Read LRE
  84576. if (use_rle) {
  84577. pixel_data = new Uint8Array(pixel_total);
  84578. var c, count, i;
  84579. var localOffset = 0;
  84580. var pixels = new Uint8Array(pixel_size);
  84581. while (offset < pixel_total && localOffset < pixel_total) {
  84582. c = data[offset++];
  84583. count = (c & 0x7f) + 1;
  84584. // RLE pixels
  84585. if (c & 0x80) {
  84586. // Bind pixel tmp array
  84587. for (i = 0; i < pixel_size; ++i) {
  84588. pixels[i] = data[offset++];
  84589. }
  84590. // Copy pixel array
  84591. for (i = 0; i < count; ++i) {
  84592. pixel_data.set(pixels, localOffset + i * pixel_size);
  84593. }
  84594. localOffset += pixel_size * count;
  84595. }
  84596. // Raw pixels
  84597. else {
  84598. count *= pixel_size;
  84599. for (i = 0; i < count; ++i) {
  84600. pixel_data[localOffset + i] = data[offset++];
  84601. }
  84602. localOffset += count;
  84603. }
  84604. }
  84605. }
  84606. // RAW Pixels
  84607. else {
  84608. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84609. }
  84610. // Load to texture
  84611. var x_start, y_start, x_step, y_step, y_end, x_end;
  84612. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84613. default:
  84614. case TGATools._ORIGIN_UL:
  84615. x_start = 0;
  84616. x_step = 1;
  84617. x_end = header.width;
  84618. y_start = 0;
  84619. y_step = 1;
  84620. y_end = header.height;
  84621. break;
  84622. case TGATools._ORIGIN_BL:
  84623. x_start = 0;
  84624. x_step = 1;
  84625. x_end = header.width;
  84626. y_start = header.height - 1;
  84627. y_step = -1;
  84628. y_end = -1;
  84629. break;
  84630. case TGATools._ORIGIN_UR:
  84631. x_start = header.width - 1;
  84632. x_step = -1;
  84633. x_end = -1;
  84634. y_start = 0;
  84635. y_step = 1;
  84636. y_end = header.height;
  84637. break;
  84638. case TGATools._ORIGIN_BR:
  84639. x_start = header.width - 1;
  84640. x_step = -1;
  84641. x_end = -1;
  84642. y_start = header.height - 1;
  84643. y_step = -1;
  84644. y_end = -1;
  84645. break;
  84646. }
  84647. // Load the specify method
  84648. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84649. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84650. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84651. };
  84652. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84653. var image = pixel_data, colormap = palettes;
  84654. var width = header.width, height = header.height;
  84655. var color, i = 0, x, y;
  84656. var imageData = new Uint8Array(width * height * 4);
  84657. for (y = y_start; y !== y_end; y += y_step) {
  84658. for (x = x_start; x !== x_end; x += x_step, i++) {
  84659. color = image[i];
  84660. imageData[(x + width * y) * 4 + 3] = 255;
  84661. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84662. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84663. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84664. }
  84665. }
  84666. return imageData;
  84667. };
  84668. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84669. var image = pixel_data;
  84670. var width = header.width, height = header.height;
  84671. var color, i = 0, x, y;
  84672. var imageData = new Uint8Array(width * height * 4);
  84673. for (y = y_start; y !== y_end; y += y_step) {
  84674. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84675. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84676. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84677. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84678. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84679. imageData[(x + width * y) * 4 + 0] = r;
  84680. imageData[(x + width * y) * 4 + 1] = g;
  84681. imageData[(x + width * y) * 4 + 2] = b;
  84682. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84683. }
  84684. }
  84685. return imageData;
  84686. };
  84687. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84688. var image = pixel_data;
  84689. var width = header.width, height = header.height;
  84690. var i = 0, x, y;
  84691. var imageData = new Uint8Array(width * height * 4);
  84692. for (y = y_start; y !== y_end; y += y_step) {
  84693. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84694. imageData[(x + width * y) * 4 + 3] = 255;
  84695. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84696. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84697. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84698. }
  84699. }
  84700. return imageData;
  84701. };
  84702. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84703. var image = pixel_data;
  84704. var width = header.width, height = header.height;
  84705. var i = 0, x, y;
  84706. var imageData = new Uint8Array(width * height * 4);
  84707. for (y = y_start; y !== y_end; y += y_step) {
  84708. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84709. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84710. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84711. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84712. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84713. }
  84714. }
  84715. return imageData;
  84716. };
  84717. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84718. var image = pixel_data;
  84719. var width = header.width, height = header.height;
  84720. var color, i = 0, x, y;
  84721. var imageData = new Uint8Array(width * height * 4);
  84722. for (y = y_start; y !== y_end; y += y_step) {
  84723. for (x = x_start; x !== x_end; x += x_step, i++) {
  84724. color = image[i];
  84725. imageData[(x + width * y) * 4 + 0] = color;
  84726. imageData[(x + width * y) * 4 + 1] = color;
  84727. imageData[(x + width * y) * 4 + 2] = color;
  84728. imageData[(x + width * y) * 4 + 3] = 255;
  84729. }
  84730. }
  84731. return imageData;
  84732. };
  84733. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84734. var image = pixel_data;
  84735. var width = header.width, height = header.height;
  84736. var i = 0, x, y;
  84737. var imageData = new Uint8Array(width * height * 4);
  84738. for (y = y_start; y !== y_end; y += y_step) {
  84739. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84740. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84741. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84742. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84743. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84744. }
  84745. }
  84746. return imageData;
  84747. };
  84748. //private static _TYPE_NO_DATA = 0;
  84749. TGATools._TYPE_INDEXED = 1;
  84750. TGATools._TYPE_RGB = 2;
  84751. TGATools._TYPE_GREY = 3;
  84752. TGATools._TYPE_RLE_INDEXED = 9;
  84753. TGATools._TYPE_RLE_RGB = 10;
  84754. TGATools._TYPE_RLE_GREY = 11;
  84755. TGATools._ORIGIN_MASK = 0x30;
  84756. TGATools._ORIGIN_SHIFT = 0x04;
  84757. TGATools._ORIGIN_BL = 0x00;
  84758. TGATools._ORIGIN_BR = 0x01;
  84759. TGATools._ORIGIN_UL = 0x02;
  84760. TGATools._ORIGIN_UR = 0x03;
  84761. return TGATools;
  84762. }());
  84763. BABYLON.TGATools = TGATools;
  84764. })(BABYLON || (BABYLON = {}));
  84765. //# sourceMappingURL=babylon.tga.js.map
  84766. var BABYLON;
  84767. (function (BABYLON) {
  84768. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84769. // All values and structures referenced from:
  84770. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84771. var DDS_MAGIC = 0x20534444;
  84772. var
  84773. //DDSD_CAPS = 0x1,
  84774. //DDSD_HEIGHT = 0x2,
  84775. //DDSD_WIDTH = 0x4,
  84776. //DDSD_PITCH = 0x8,
  84777. //DDSD_PIXELFORMAT = 0x1000,
  84778. DDSD_MIPMAPCOUNT = 0x20000;
  84779. //DDSD_LINEARSIZE = 0x80000,
  84780. //DDSD_DEPTH = 0x800000;
  84781. // var DDSCAPS_COMPLEX = 0x8,
  84782. // DDSCAPS_MIPMAP = 0x400000,
  84783. // DDSCAPS_TEXTURE = 0x1000;
  84784. var DDSCAPS2_CUBEMAP = 0x200;
  84785. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84786. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84787. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84788. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84789. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84790. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84791. // DDSCAPS2_VOLUME = 0x200000;
  84792. var
  84793. //DDPF_ALPHAPIXELS = 0x1,
  84794. //DDPF_ALPHA = 0x2,
  84795. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84796. //DDPF_YUV = 0x200,
  84797. DDPF_LUMINANCE = 0x20000;
  84798. function FourCCToInt32(value) {
  84799. return value.charCodeAt(0) +
  84800. (value.charCodeAt(1) << 8) +
  84801. (value.charCodeAt(2) << 16) +
  84802. (value.charCodeAt(3) << 24);
  84803. }
  84804. function Int32ToFourCC(value) {
  84805. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84806. }
  84807. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84808. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84809. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84810. var FOURCC_DX10 = FourCCToInt32("DX10");
  84811. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84812. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84813. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84814. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84815. var headerLengthInt = 31; // The header length in 32 bit ints
  84816. // Offsets into the header array
  84817. var off_magic = 0;
  84818. var off_size = 1;
  84819. var off_flags = 2;
  84820. var off_height = 3;
  84821. var off_width = 4;
  84822. var off_mipmapCount = 7;
  84823. var off_pfFlags = 20;
  84824. var off_pfFourCC = 21;
  84825. var off_RGBbpp = 22;
  84826. var off_RMask = 23;
  84827. var off_GMask = 24;
  84828. var off_BMask = 25;
  84829. var off_AMask = 26;
  84830. // var off_caps1 = 27;
  84831. var off_caps2 = 28;
  84832. // var off_caps3 = 29;
  84833. // var off_caps4 = 30;
  84834. var off_dxgiFormat = 32;
  84835. ;
  84836. var DDSTools = /** @class */ (function () {
  84837. function DDSTools() {
  84838. }
  84839. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84840. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84841. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84842. var mipmapCount = 1;
  84843. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84844. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84845. }
  84846. var fourCC = header[off_pfFourCC];
  84847. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84848. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84849. switch (fourCC) {
  84850. case FOURCC_D3DFMT_R16G16B16A16F:
  84851. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84852. break;
  84853. case FOURCC_D3DFMT_R32G32B32A32F:
  84854. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84855. break;
  84856. case FOURCC_DX10:
  84857. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84858. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84859. break;
  84860. }
  84861. }
  84862. return {
  84863. width: header[off_width],
  84864. height: header[off_height],
  84865. mipmapCount: mipmapCount,
  84866. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84867. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84868. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84869. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84870. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84871. dxgiFormat: dxgiFormat,
  84872. textureType: textureType
  84873. };
  84874. };
  84875. DDSTools._ToHalfFloat = function (value) {
  84876. if (!DDSTools._FloatView) {
  84877. DDSTools._FloatView = new Float32Array(1);
  84878. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84879. }
  84880. DDSTools._FloatView[0] = value;
  84881. var x = DDSTools._Int32View[0];
  84882. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84883. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84884. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84885. /* If zero, or denormal, or exponent underflows too much for a denormal
  84886. * half, return signed zero. */
  84887. if (e < 103) {
  84888. return bits;
  84889. }
  84890. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84891. if (e > 142) {
  84892. bits |= 0x7c00;
  84893. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84894. * not Inf, so make sure we set one mantissa bit too. */
  84895. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84896. return bits;
  84897. }
  84898. /* If exponent underflows but not too much, return a denormal */
  84899. if (e < 113) {
  84900. m |= 0x0800;
  84901. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84902. * to 1, which is OK. */
  84903. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84904. return bits;
  84905. }
  84906. bits |= ((e - 112) << 10) | (m >> 1);
  84907. bits += m & 1;
  84908. return bits;
  84909. };
  84910. DDSTools._FromHalfFloat = function (value) {
  84911. var s = (value & 0x8000) >> 15;
  84912. var e = (value & 0x7C00) >> 10;
  84913. var f = value & 0x03FF;
  84914. if (e === 0) {
  84915. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84916. }
  84917. else if (e == 0x1F) {
  84918. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84919. }
  84920. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84921. };
  84922. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84923. var destArray = new Float32Array(dataLength);
  84924. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84925. var index = 0;
  84926. for (var y = 0; y < height; y++) {
  84927. for (var x = 0; x < width; x++) {
  84928. var srcPos = (x + y * width) * 4;
  84929. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84930. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84931. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84932. if (DDSTools.StoreLODInAlphaChannel) {
  84933. destArray[index + 3] = lod;
  84934. }
  84935. else {
  84936. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84937. }
  84938. index += 4;
  84939. }
  84940. }
  84941. return destArray;
  84942. };
  84943. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84944. if (DDSTools.StoreLODInAlphaChannel) {
  84945. var destArray = new Uint16Array(dataLength);
  84946. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84947. var index = 0;
  84948. for (var y = 0; y < height; y++) {
  84949. for (var x = 0; x < width; x++) {
  84950. var srcPos = (x + y * width) * 4;
  84951. destArray[index] = srcData[srcPos];
  84952. destArray[index + 1] = srcData[srcPos + 1];
  84953. destArray[index + 2] = srcData[srcPos + 2];
  84954. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84955. index += 4;
  84956. }
  84957. }
  84958. return destArray;
  84959. }
  84960. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84961. };
  84962. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84963. if (DDSTools.StoreLODInAlphaChannel) {
  84964. var destArray = new Float32Array(dataLength);
  84965. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84966. var index = 0;
  84967. for (var y = 0; y < height; y++) {
  84968. for (var x = 0; x < width; x++) {
  84969. var srcPos = (x + y * width) * 4;
  84970. destArray[index] = srcData[srcPos];
  84971. destArray[index + 1] = srcData[srcPos + 1];
  84972. destArray[index + 2] = srcData[srcPos + 2];
  84973. destArray[index + 3] = lod;
  84974. index += 4;
  84975. }
  84976. }
  84977. return destArray;
  84978. }
  84979. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84980. };
  84981. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84982. var destArray = new Uint8Array(dataLength);
  84983. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84984. var index = 0;
  84985. for (var y = 0; y < height; y++) {
  84986. for (var x = 0; x < width; x++) {
  84987. var srcPos = (x + y * width) * 4;
  84988. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84989. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84990. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84991. if (DDSTools.StoreLODInAlphaChannel) {
  84992. destArray[index + 3] = lod;
  84993. }
  84994. else {
  84995. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84996. }
  84997. index += 4;
  84998. }
  84999. }
  85000. return destArray;
  85001. };
  85002. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85003. var destArray = new Uint8Array(dataLength);
  85004. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85005. var index = 0;
  85006. for (var y = 0; y < height; y++) {
  85007. for (var x = 0; x < width; x++) {
  85008. var srcPos = (x + y * width) * 4;
  85009. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85010. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85011. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85012. if (DDSTools.StoreLODInAlphaChannel) {
  85013. destArray[index + 3] = lod;
  85014. }
  85015. else {
  85016. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85017. }
  85018. index += 4;
  85019. }
  85020. }
  85021. return destArray;
  85022. };
  85023. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85024. var byteArray = new Uint8Array(dataLength);
  85025. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85026. var index = 0;
  85027. for (var y = 0; y < height; y++) {
  85028. for (var x = 0; x < width; x++) {
  85029. var srcPos = (x + y * width) * 4;
  85030. byteArray[index] = srcData[srcPos + rOffset];
  85031. byteArray[index + 1] = srcData[srcPos + gOffset];
  85032. byteArray[index + 2] = srcData[srcPos + bOffset];
  85033. byteArray[index + 3] = srcData[srcPos + aOffset];
  85034. index += 4;
  85035. }
  85036. }
  85037. return byteArray;
  85038. };
  85039. DDSTools._ExtractLongWordOrder = function (value) {
  85040. if (value === 0 || value === 255 || value === -16777216) {
  85041. return 0;
  85042. }
  85043. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85044. };
  85045. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85046. var byteArray = new Uint8Array(dataLength);
  85047. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85048. var index = 0;
  85049. for (var y = 0; y < height; y++) {
  85050. for (var x = 0; x < width; x++) {
  85051. var srcPos = (x + y * width) * 3;
  85052. byteArray[index] = srcData[srcPos + rOffset];
  85053. byteArray[index + 1] = srcData[srcPos + gOffset];
  85054. byteArray[index + 2] = srcData[srcPos + bOffset];
  85055. index += 3;
  85056. }
  85057. }
  85058. return byteArray;
  85059. };
  85060. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85061. var byteArray = new Uint8Array(dataLength);
  85062. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85063. var index = 0;
  85064. for (var y = 0; y < height; y++) {
  85065. for (var x = 0; x < width; x++) {
  85066. var srcPos = (x + y * width);
  85067. byteArray[index] = srcData[srcPos];
  85068. index++;
  85069. }
  85070. }
  85071. return byteArray;
  85072. };
  85073. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85074. if (lodIndex === void 0) { lodIndex = -1; }
  85075. var sphericalPolynomialFaces = null;
  85076. if (info.sphericalPolynomial) {
  85077. sphericalPolynomialFaces = new Array();
  85078. }
  85079. var ext = engine.getCaps().s3tc;
  85080. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85081. var fourCC, width, height, dataLength = 0, dataOffset;
  85082. var byteArray, mipmapCount, mip;
  85083. var internalFormat = 0;
  85084. var format = 0;
  85085. var blockBytes = 1;
  85086. if (header[off_magic] !== DDS_MAGIC) {
  85087. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85088. return;
  85089. }
  85090. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85091. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85092. return;
  85093. }
  85094. if (info.isCompressed && !ext) {
  85095. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85096. return;
  85097. }
  85098. var bpp = header[off_RGBbpp];
  85099. dataOffset = header[off_size] + 4;
  85100. var computeFormats = false;
  85101. if (info.isFourCC) {
  85102. fourCC = header[off_pfFourCC];
  85103. switch (fourCC) {
  85104. case FOURCC_DXT1:
  85105. blockBytes = 8;
  85106. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85107. break;
  85108. case FOURCC_DXT3:
  85109. blockBytes = 16;
  85110. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85111. break;
  85112. case FOURCC_DXT5:
  85113. blockBytes = 16;
  85114. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85115. break;
  85116. case FOURCC_D3DFMT_R16G16B16A16F:
  85117. computeFormats = true;
  85118. break;
  85119. case FOURCC_D3DFMT_R32G32B32A32F:
  85120. computeFormats = true;
  85121. break;
  85122. case FOURCC_DX10:
  85123. // There is an additionnal header so dataOffset need to be changed
  85124. dataOffset += 5 * 4; // 5 uints
  85125. var supported = false;
  85126. switch (info.dxgiFormat) {
  85127. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85128. computeFormats = true;
  85129. supported = true;
  85130. break;
  85131. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85132. info.isRGB = true;
  85133. info.isFourCC = false;
  85134. bpp = 32;
  85135. supported = true;
  85136. break;
  85137. }
  85138. if (supported) {
  85139. break;
  85140. }
  85141. default:
  85142. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85143. return;
  85144. }
  85145. }
  85146. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85147. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85148. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85149. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85150. if (computeFormats) {
  85151. format = engine._getWebGLTextureType(info.textureType);
  85152. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85153. }
  85154. mipmapCount = 1;
  85155. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85156. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85157. }
  85158. for (var face = 0; face < faces; face++) {
  85159. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85160. width = header[off_width];
  85161. height = header[off_height];
  85162. for (mip = 0; mip < mipmapCount; ++mip) {
  85163. if (lodIndex === -1 || lodIndex === mip) {
  85164. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85165. var i = (lodIndex === -1) ? mip : 0;
  85166. if (!info.isCompressed && info.isFourCC) {
  85167. dataLength = width * height * 4;
  85168. var floatArray = null;
  85169. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85170. if (bpp === 128) {
  85171. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85172. if (sphericalPolynomialFaces && i == 0) {
  85173. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85174. }
  85175. }
  85176. else if (bpp === 64) {
  85177. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85178. if (sphericalPolynomialFaces && i == 0) {
  85179. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85180. }
  85181. }
  85182. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85183. format = engine._getWebGLTextureType(info.textureType);
  85184. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85185. }
  85186. else {
  85187. if (bpp === 128) {
  85188. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85189. if (sphericalPolynomialFaces && i == 0) {
  85190. sphericalPolynomialFaces.push(floatArray);
  85191. }
  85192. }
  85193. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85194. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85195. if (sphericalPolynomialFaces && i == 0) {
  85196. sphericalPolynomialFaces.push(floatArray);
  85197. }
  85198. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85199. format = engine._getWebGLTextureType(info.textureType);
  85200. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85201. }
  85202. else { // 64
  85203. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85204. if (sphericalPolynomialFaces && i == 0) {
  85205. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85206. }
  85207. }
  85208. }
  85209. if (floatArray) {
  85210. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85211. }
  85212. }
  85213. else if (info.isRGB) {
  85214. if (bpp === 24) {
  85215. dataLength = width * height * 3;
  85216. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85217. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85218. }
  85219. else { // 32
  85220. dataLength = width * height * 4;
  85221. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85222. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85223. }
  85224. }
  85225. else if (info.isLuminance) {
  85226. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85227. var unpaddedRowSize = width;
  85228. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85229. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85230. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85231. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85232. }
  85233. else {
  85234. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85235. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85236. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85237. }
  85238. }
  85239. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85240. width *= 0.5;
  85241. height *= 0.5;
  85242. width = Math.max(1.0, width);
  85243. height = Math.max(1.0, height);
  85244. }
  85245. if (currentFace !== undefined) {
  85246. // Loading a single face
  85247. break;
  85248. }
  85249. }
  85250. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85251. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85252. size: header[off_width],
  85253. right: sphericalPolynomialFaces[0],
  85254. left: sphericalPolynomialFaces[1],
  85255. up: sphericalPolynomialFaces[2],
  85256. down: sphericalPolynomialFaces[3],
  85257. front: sphericalPolynomialFaces[4],
  85258. back: sphericalPolynomialFaces[5],
  85259. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85260. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85261. gammaSpace: false,
  85262. });
  85263. }
  85264. else {
  85265. info.sphericalPolynomial = undefined;
  85266. }
  85267. };
  85268. DDSTools.StoreLODInAlphaChannel = false;
  85269. return DDSTools;
  85270. }());
  85271. BABYLON.DDSTools = DDSTools;
  85272. })(BABYLON || (BABYLON = {}));
  85273. //# sourceMappingURL=babylon.dds.js.map
  85274. var BABYLON;
  85275. (function (BABYLON) {
  85276. /**
  85277. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  85278. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  85279. */
  85280. var KhronosTextureContainer = /** @class */ (function () {
  85281. /**
  85282. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  85283. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  85284. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  85285. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  85286. */
  85287. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85288. this.arrayBuffer = arrayBuffer;
  85289. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85290. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85291. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85292. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85293. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85294. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85295. BABYLON.Tools.Error("texture missing KTX identifier");
  85296. return;
  85297. }
  85298. // load the reset of the header in native 32 bit int
  85299. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85300. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85301. var oppositeEndianess = header[0] === 0x01020304;
  85302. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85303. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85304. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85305. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85306. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85307. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85308. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85309. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85310. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85311. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85312. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85313. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85314. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85315. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85316. if (this.glType !== 0) {
  85317. BABYLON.Tools.Error("only compressed formats currently supported");
  85318. return;
  85319. }
  85320. else {
  85321. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85322. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85323. }
  85324. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85325. BABYLON.Tools.Error("only 2D textures currently supported");
  85326. return;
  85327. }
  85328. if (this.numberOfArrayElements !== 0) {
  85329. BABYLON.Tools.Error("texture arrays not currently supported");
  85330. return;
  85331. }
  85332. if (this.numberOfFaces !== facesExpected) {
  85333. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85334. return;
  85335. }
  85336. // we now have a completely validated file, so could use existence of loadType as success
  85337. // would need to make this more elaborate & adjust checks above to support more than one load type
  85338. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85339. }
  85340. // not as fast hardware based, but will probably never need to use
  85341. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85342. return ((val & 0xFF) << 24)
  85343. | ((val & 0xFF00) << 8)
  85344. | ((val >> 8) & 0xFF00)
  85345. | ((val >> 24) & 0xFF);
  85346. };
  85347. /**
  85348. * It is assumed that the texture has already been created & is currently bound
  85349. */
  85350. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85351. switch (this.loadType) {
  85352. case KhronosTextureContainer.COMPRESSED_2D:
  85353. this._upload2DCompressedLevels(gl, loadMipmaps);
  85354. break;
  85355. case KhronosTextureContainer.TEX_2D:
  85356. case KhronosTextureContainer.COMPRESSED_3D:
  85357. case KhronosTextureContainer.TEX_3D:
  85358. }
  85359. };
  85360. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85361. // initialize width & height for level 1
  85362. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85363. var width = this.pixelWidth;
  85364. var height = this.pixelHeight;
  85365. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85366. for (var level = 0; level < mipmapCount; level++) {
  85367. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85368. for (var face = 0; face < this.numberOfFaces; face++) {
  85369. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85370. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85371. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85372. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85373. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85374. }
  85375. width = Math.max(1.0, width * 0.5);
  85376. height = Math.max(1.0, height * 0.5);
  85377. }
  85378. };
  85379. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85380. // load types
  85381. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85382. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85383. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85384. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85385. return KhronosTextureContainer;
  85386. }());
  85387. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85388. })(BABYLON || (BABYLON = {}));
  85389. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85390. var BABYLON;
  85391. (function (BABYLON) {
  85392. var Debug;
  85393. (function (Debug) {
  85394. /**
  85395. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  85396. */
  85397. var SkeletonViewer = /** @class */ (function () {
  85398. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  85399. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85400. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85401. this.skeleton = skeleton;
  85402. this.mesh = mesh;
  85403. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85404. this.renderingGroupId = renderingGroupId;
  85405. this.color = BABYLON.Color3.White();
  85406. this._debugLines = new Array();
  85407. this._isEnabled = false;
  85408. this._scene = scene;
  85409. this.update();
  85410. this._renderFunction = this.update.bind(this);
  85411. }
  85412. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85413. get: function () {
  85414. return this._isEnabled;
  85415. },
  85416. set: function (value) {
  85417. if (this._isEnabled === value) {
  85418. return;
  85419. }
  85420. this._isEnabled = value;
  85421. if (value) {
  85422. this._scene.registerBeforeRender(this._renderFunction);
  85423. }
  85424. else {
  85425. this._scene.unregisterBeforeRender(this._renderFunction);
  85426. }
  85427. },
  85428. enumerable: true,
  85429. configurable: true
  85430. });
  85431. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85432. if (x === void 0) { x = 0; }
  85433. if (y === void 0) { y = 0; }
  85434. if (z === void 0) { z = 0; }
  85435. var tmat = BABYLON.Tmp.Matrix[0];
  85436. var parentBone = bone.getParent();
  85437. tmat.copyFrom(bone.getLocalMatrix());
  85438. if (x !== 0 || y !== 0 || z !== 0) {
  85439. var tmat2 = BABYLON.Tmp.Matrix[1];
  85440. BABYLON.Matrix.IdentityToRef(tmat2);
  85441. tmat2.m[12] = x;
  85442. tmat2.m[13] = y;
  85443. tmat2.m[14] = z;
  85444. tmat2.multiplyToRef(tmat, tmat);
  85445. }
  85446. if (parentBone) {
  85447. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85448. }
  85449. tmat.multiplyToRef(meshMat, tmat);
  85450. position.x = tmat.m[12];
  85451. position.y = tmat.m[13];
  85452. position.z = tmat.m[14];
  85453. };
  85454. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85455. var len = bones.length;
  85456. var meshPos = this.mesh.position;
  85457. for (var i = 0; i < len; i++) {
  85458. var bone = bones[i];
  85459. var points = this._debugLines[i];
  85460. if (!points) {
  85461. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85462. this._debugLines[i] = points;
  85463. }
  85464. this._getBonePosition(points[0], bone, meshMat);
  85465. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85466. points[0].subtractInPlace(meshPos);
  85467. points[1].subtractInPlace(meshPos);
  85468. }
  85469. };
  85470. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85471. var len = bones.length;
  85472. var boneNum = 0;
  85473. var meshPos = this.mesh.position;
  85474. for (var i = len - 1; i >= 0; i--) {
  85475. var childBone = bones[i];
  85476. var parentBone = childBone.getParent();
  85477. if (!parentBone) {
  85478. continue;
  85479. }
  85480. var points = this._debugLines[boneNum];
  85481. if (!points) {
  85482. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85483. this._debugLines[boneNum] = points;
  85484. }
  85485. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85486. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85487. points[0].subtractInPlace(meshPos);
  85488. points[1].subtractInPlace(meshPos);
  85489. boneNum++;
  85490. }
  85491. };
  85492. SkeletonViewer.prototype.update = function () {
  85493. if (this.autoUpdateBonesMatrices) {
  85494. this.skeleton.computeAbsoluteTransforms();
  85495. }
  85496. if (this.skeleton.bones[0].length === undefined) {
  85497. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85498. }
  85499. else {
  85500. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85501. }
  85502. if (!this._debugMesh) {
  85503. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85504. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85505. }
  85506. else {
  85507. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85508. }
  85509. this._debugMesh.position.copyFrom(this.mesh.position);
  85510. this._debugMesh.color = this.color;
  85511. };
  85512. SkeletonViewer.prototype.dispose = function () {
  85513. if (this._debugMesh) {
  85514. this.isEnabled = false;
  85515. this._debugMesh.dispose();
  85516. this._debugMesh = null;
  85517. }
  85518. };
  85519. return SkeletonViewer;
  85520. }());
  85521. Debug.SkeletonViewer = SkeletonViewer;
  85522. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85523. })(BABYLON || (BABYLON = {}));
  85524. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85525. /**
  85526. * Module Debug contains the (visual) components to debug a scene correctly
  85527. */
  85528. var BABYLON;
  85529. (function (BABYLON) {
  85530. var Debug;
  85531. (function (Debug) {
  85532. /**
  85533. * The Axes viewer will show 3 axes in a specific point in space
  85534. */
  85535. var AxesViewer = /** @class */ (function () {
  85536. function AxesViewer(scene, scaleLines) {
  85537. if (scaleLines === void 0) { scaleLines = 1; }
  85538. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85539. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85540. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85541. this.scaleLines = 1;
  85542. this.scaleLines = scaleLines;
  85543. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85544. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85545. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85546. this._xmesh.renderingGroupId = 2;
  85547. this._ymesh.renderingGroupId = 2;
  85548. this._zmesh.renderingGroupId = 2;
  85549. this._xmesh.material.checkReadyOnlyOnce = true;
  85550. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85551. this._ymesh.material.checkReadyOnlyOnce = true;
  85552. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85553. this._zmesh.material.checkReadyOnlyOnce = true;
  85554. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85555. this.scene = scene;
  85556. }
  85557. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85558. var scaleLines = this.scaleLines;
  85559. if (this._xmesh) {
  85560. this._xmesh.position.copyFrom(position);
  85561. }
  85562. if (this._ymesh) {
  85563. this._ymesh.position.copyFrom(position);
  85564. }
  85565. if (this._zmesh) {
  85566. this._zmesh.position.copyFrom(position);
  85567. }
  85568. var point2 = this._xline[1];
  85569. point2.x = xaxis.x * scaleLines;
  85570. point2.y = xaxis.y * scaleLines;
  85571. point2.z = xaxis.z * scaleLines;
  85572. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85573. point2 = this._yline[1];
  85574. point2.x = yaxis.x * scaleLines;
  85575. point2.y = yaxis.y * scaleLines;
  85576. point2.z = yaxis.z * scaleLines;
  85577. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85578. point2 = this._zline[1];
  85579. point2.x = zaxis.x * scaleLines;
  85580. point2.y = zaxis.y * scaleLines;
  85581. point2.z = zaxis.z * scaleLines;
  85582. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85583. };
  85584. AxesViewer.prototype.dispose = function () {
  85585. if (this._xmesh) {
  85586. this._xmesh.dispose();
  85587. }
  85588. if (this._ymesh) {
  85589. this._ymesh.dispose();
  85590. }
  85591. if (this._zmesh) {
  85592. this._zmesh.dispose();
  85593. }
  85594. this._xmesh = null;
  85595. this._ymesh = null;
  85596. this._zmesh = null;
  85597. this.scene = null;
  85598. };
  85599. return AxesViewer;
  85600. }());
  85601. Debug.AxesViewer = AxesViewer;
  85602. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85603. })(BABYLON || (BABYLON = {}));
  85604. //# sourceMappingURL=babylon.axesViewer.js.map
  85605. var BABYLON;
  85606. (function (BABYLON) {
  85607. var Debug;
  85608. (function (Debug) {
  85609. /**
  85610. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85611. */
  85612. var BoneAxesViewer = /** @class */ (function (_super) {
  85613. __extends(BoneAxesViewer, _super);
  85614. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85615. if (scaleLines === void 0) { scaleLines = 1; }
  85616. var _this = _super.call(this, scene, scaleLines) || this;
  85617. _this.pos = BABYLON.Vector3.Zero();
  85618. _this.xaxis = BABYLON.Vector3.Zero();
  85619. _this.yaxis = BABYLON.Vector3.Zero();
  85620. _this.zaxis = BABYLON.Vector3.Zero();
  85621. _this.mesh = mesh;
  85622. _this.bone = bone;
  85623. return _this;
  85624. }
  85625. BoneAxesViewer.prototype.update = function () {
  85626. if (!this.mesh || !this.bone) {
  85627. return;
  85628. }
  85629. var bone = this.bone;
  85630. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85631. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85632. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85633. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85634. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85635. };
  85636. BoneAxesViewer.prototype.dispose = function () {
  85637. if (this.mesh) {
  85638. this.mesh = null;
  85639. this.bone = null;
  85640. _super.prototype.dispose.call(this);
  85641. }
  85642. };
  85643. return BoneAxesViewer;
  85644. }(Debug.AxesViewer));
  85645. Debug.BoneAxesViewer = BoneAxesViewer;
  85646. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85647. })(BABYLON || (BABYLON = {}));
  85648. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85649. var BABYLON;
  85650. (function (BABYLON) {
  85651. var RayHelper = /** @class */ (function () {
  85652. function RayHelper(ray) {
  85653. this.ray = ray;
  85654. }
  85655. RayHelper.CreateAndShow = function (ray, scene, color) {
  85656. var helper = new RayHelper(ray);
  85657. helper.show(scene, color);
  85658. return helper;
  85659. };
  85660. RayHelper.prototype.show = function (scene, color) {
  85661. if (!this._renderFunction && this.ray) {
  85662. var ray = this.ray;
  85663. this._renderFunction = this._render.bind(this);
  85664. this._scene = scene;
  85665. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85666. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85667. if (this._renderFunction) {
  85668. this._scene.registerBeforeRender(this._renderFunction);
  85669. }
  85670. }
  85671. if (color && this._renderLine) {
  85672. this._renderLine.color.copyFrom(color);
  85673. }
  85674. };
  85675. RayHelper.prototype.hide = function () {
  85676. if (this._renderFunction && this._scene) {
  85677. this._scene.unregisterBeforeRender(this._renderFunction);
  85678. this._scene = null;
  85679. this._renderFunction = null;
  85680. if (this._renderLine) {
  85681. this._renderLine.dispose();
  85682. this._renderLine = null;
  85683. }
  85684. this._renderPoints = [];
  85685. }
  85686. };
  85687. RayHelper.prototype._render = function () {
  85688. var ray = this.ray;
  85689. if (!ray) {
  85690. return;
  85691. }
  85692. var point = this._renderPoints[1];
  85693. var len = Math.min(ray.length, 1000000);
  85694. point.copyFrom(ray.direction);
  85695. point.scaleInPlace(len);
  85696. point.addInPlace(ray.origin);
  85697. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85698. };
  85699. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85700. this._attachedToMesh = mesh;
  85701. var ray = this.ray;
  85702. if (!ray) {
  85703. return;
  85704. }
  85705. if (!ray.direction) {
  85706. ray.direction = BABYLON.Vector3.Zero();
  85707. }
  85708. if (!ray.origin) {
  85709. ray.origin = BABYLON.Vector3.Zero();
  85710. }
  85711. if (length) {
  85712. ray.length = length;
  85713. }
  85714. if (!meshSpaceOrigin) {
  85715. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85716. }
  85717. if (!meshSpaceDirection) {
  85718. // -1 so that this will work with Mesh.lookAt
  85719. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85720. }
  85721. if (!this._meshSpaceDirection) {
  85722. this._meshSpaceDirection = meshSpaceDirection.clone();
  85723. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85724. }
  85725. else {
  85726. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85727. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85728. }
  85729. if (!this._updateToMeshFunction) {
  85730. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85731. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85732. }
  85733. this._updateToMesh();
  85734. };
  85735. RayHelper.prototype.detachFromMesh = function () {
  85736. if (this._attachedToMesh) {
  85737. if (this._updateToMeshFunction) {
  85738. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85739. }
  85740. this._attachedToMesh = null;
  85741. this._updateToMeshFunction = null;
  85742. }
  85743. };
  85744. RayHelper.prototype._updateToMesh = function () {
  85745. var ray = this.ray;
  85746. if (!this._attachedToMesh || !ray) {
  85747. return;
  85748. }
  85749. if (this._attachedToMesh._isDisposed) {
  85750. this.detachFromMesh();
  85751. return;
  85752. }
  85753. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85754. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85755. };
  85756. RayHelper.prototype.dispose = function () {
  85757. this.hide();
  85758. this.detachFromMesh();
  85759. this.ray = null;
  85760. };
  85761. return RayHelper;
  85762. }());
  85763. BABYLON.RayHelper = RayHelper;
  85764. })(BABYLON || (BABYLON = {}));
  85765. //# sourceMappingURL=babylon.rayHelper.js.map
  85766. var BABYLON;
  85767. (function (BABYLON) {
  85768. // load the inspector using require, if not present in the global namespace.
  85769. var DebugLayer = /** @class */ (function () {
  85770. function DebugLayer(scene) {
  85771. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85772. this._scene = scene;
  85773. // load inspector using require, if it doesn't exist on the global namespace.
  85774. }
  85775. /** Creates the inspector window. */
  85776. DebugLayer.prototype._createInspector = function (config) {
  85777. if (config === void 0) { config = {}; }
  85778. var popup = config.popup || false;
  85779. var initialTab = config.initialTab || 0;
  85780. var parentElement = config.parentElement || null;
  85781. if (!this._inspector) {
  85782. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85783. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85784. } // else nothing to do,; instance is already existing
  85785. };
  85786. DebugLayer.prototype.isVisible = function () {
  85787. if (!this._inspector) {
  85788. return false;
  85789. }
  85790. return true;
  85791. };
  85792. DebugLayer.prototype.hide = function () {
  85793. if (this._inspector) {
  85794. try {
  85795. this._inspector.dispose();
  85796. }
  85797. catch (e) {
  85798. // If the inspector has been removed directly from the inspector tool
  85799. }
  85800. this._inspector = null;
  85801. }
  85802. };
  85803. DebugLayer.prototype.show = function (config) {
  85804. if (config === void 0) { config = {}; }
  85805. if (typeof this.BJSINSPECTOR == 'undefined') {
  85806. // Load inspector and add it to the DOM
  85807. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85808. }
  85809. else {
  85810. // Otherwise creates the inspector
  85811. this._createInspector(config);
  85812. }
  85813. };
  85814. /**
  85815. * Gets the active tab
  85816. * @return the index of the active tab or -1 if the inspector is hidden
  85817. */
  85818. DebugLayer.prototype.getActiveTab = function () {
  85819. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  85820. };
  85821. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85822. return DebugLayer;
  85823. }());
  85824. BABYLON.DebugLayer = DebugLayer;
  85825. })(BABYLON || (BABYLON = {}));
  85826. //# sourceMappingURL=babylon.debugLayer.js.map
  85827. var BABYLON;
  85828. (function (BABYLON) {
  85829. var Debug;
  85830. (function (Debug) {
  85831. /**
  85832. * Used to show the physics impostor around the specific mesh.
  85833. */
  85834. var PhysicsViewer = /** @class */ (function () {
  85835. function PhysicsViewer(scene) {
  85836. this._impostors = [];
  85837. this._meshes = [];
  85838. this._numMeshes = 0;
  85839. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85840. var physicEngine = this._scene.getPhysicsEngine();
  85841. if (physicEngine) {
  85842. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85843. }
  85844. }
  85845. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85846. var plugin = this._physicsEnginePlugin;
  85847. for (var i = 0; i < this._numMeshes; i++) {
  85848. var impostor = this._impostors[i];
  85849. if (!impostor) {
  85850. continue;
  85851. }
  85852. if (impostor.isDisposed) {
  85853. this.hideImpostor(this._impostors[i--]);
  85854. }
  85855. else {
  85856. var mesh = this._meshes[i];
  85857. if (mesh && plugin) {
  85858. plugin.syncMeshWithImpostor(mesh, impostor);
  85859. }
  85860. }
  85861. }
  85862. };
  85863. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85864. if (!this._scene) {
  85865. return;
  85866. }
  85867. for (var i = 0; i < this._numMeshes; i++) {
  85868. if (this._impostors[i] == impostor) {
  85869. return;
  85870. }
  85871. }
  85872. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85873. if (debugMesh) {
  85874. this._impostors[this._numMeshes] = impostor;
  85875. this._meshes[this._numMeshes] = debugMesh;
  85876. if (this._numMeshes === 0) {
  85877. this._renderFunction = this._updateDebugMeshes.bind(this);
  85878. this._scene.registerBeforeRender(this._renderFunction);
  85879. }
  85880. this._numMeshes++;
  85881. }
  85882. };
  85883. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85884. if (!impostor || !this._scene) {
  85885. return;
  85886. }
  85887. var removed = false;
  85888. for (var i = 0; i < this._numMeshes; i++) {
  85889. if (this._impostors[i] == impostor) {
  85890. var mesh = this._meshes[i];
  85891. if (!mesh) {
  85892. continue;
  85893. }
  85894. this._scene.removeMesh(mesh);
  85895. mesh.dispose();
  85896. this._numMeshes--;
  85897. if (this._numMeshes > 0) {
  85898. this._meshes[i] = this._meshes[this._numMeshes];
  85899. this._impostors[i] = this._impostors[this._numMeshes];
  85900. this._meshes[this._numMeshes] = null;
  85901. this._impostors[this._numMeshes] = null;
  85902. }
  85903. else {
  85904. this._meshes[0] = null;
  85905. this._impostors[0] = null;
  85906. }
  85907. removed = true;
  85908. break;
  85909. }
  85910. }
  85911. if (removed && this._numMeshes === 0) {
  85912. this._scene.unregisterBeforeRender(this._renderFunction);
  85913. }
  85914. };
  85915. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85916. if (!this._debugMaterial) {
  85917. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85918. this._debugMaterial.wireframe = true;
  85919. }
  85920. return this._debugMaterial;
  85921. };
  85922. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85923. if (!this._debugBoxMesh) {
  85924. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85925. this._debugBoxMesh.renderingGroupId = 1;
  85926. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85927. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85928. scene.removeMesh(this._debugBoxMesh);
  85929. }
  85930. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85931. };
  85932. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85933. if (!this._debugSphereMesh) {
  85934. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85935. this._debugSphereMesh.renderingGroupId = 1;
  85936. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85937. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85938. scene.removeMesh(this._debugSphereMesh);
  85939. }
  85940. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85941. };
  85942. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85943. var mesh = null;
  85944. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85945. mesh = this._getDebugBoxMesh(scene);
  85946. impostor.getBoxSizeToRef(mesh.scaling);
  85947. }
  85948. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85949. mesh = this._getDebugSphereMesh(scene);
  85950. var radius = impostor.getRadius();
  85951. mesh.scaling.x = radius * 2;
  85952. mesh.scaling.y = radius * 2;
  85953. mesh.scaling.z = radius * 2;
  85954. }
  85955. return mesh;
  85956. };
  85957. PhysicsViewer.prototype.dispose = function () {
  85958. for (var i = 0; i < this._numMeshes; i++) {
  85959. this.hideImpostor(this._impostors[i]);
  85960. }
  85961. if (this._debugBoxMesh) {
  85962. this._debugBoxMesh.dispose();
  85963. }
  85964. if (this._debugSphereMesh) {
  85965. this._debugSphereMesh.dispose();
  85966. }
  85967. if (this._debugMaterial) {
  85968. this._debugMaterial.dispose();
  85969. }
  85970. this._impostors.length = 0;
  85971. this._scene = null;
  85972. this._physicsEnginePlugin = null;
  85973. };
  85974. return PhysicsViewer;
  85975. }());
  85976. Debug.PhysicsViewer = PhysicsViewer;
  85977. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85978. })(BABYLON || (BABYLON = {}));
  85979. //# sourceMappingURL=babylon.physicsViewer.js.map
  85980. var BABYLON;
  85981. (function (BABYLON) {
  85982. var BoundingBoxRenderer = /** @class */ (function () {
  85983. function BoundingBoxRenderer(scene) {
  85984. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85985. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85986. this.showBackLines = true;
  85987. this.renderList = new BABYLON.SmartArray(32);
  85988. this._vertexBuffers = {};
  85989. this._scene = scene;
  85990. }
  85991. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85992. if (this._colorShader) {
  85993. return;
  85994. }
  85995. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85996. attributes: [BABYLON.VertexBuffer.PositionKind],
  85997. uniforms: ["world", "viewProjection", "color"]
  85998. });
  85999. var engine = this._scene.getEngine();
  86000. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86001. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86002. this._createIndexBuffer();
  86003. };
  86004. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86005. var engine = this._scene.getEngine();
  86006. 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]);
  86007. };
  86008. BoundingBoxRenderer.prototype._rebuild = function () {
  86009. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86010. if (vb) {
  86011. vb._rebuild();
  86012. }
  86013. this._createIndexBuffer();
  86014. };
  86015. BoundingBoxRenderer.prototype.reset = function () {
  86016. this.renderList.reset();
  86017. };
  86018. BoundingBoxRenderer.prototype.render = function () {
  86019. if (this.renderList.length === 0) {
  86020. return;
  86021. }
  86022. this._prepareRessources();
  86023. if (!this._colorShader.isReady()) {
  86024. return;
  86025. }
  86026. var engine = this._scene.getEngine();
  86027. engine.setDepthWrite(false);
  86028. this._colorShader._preBind();
  86029. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86030. var boundingBox = this.renderList.data[boundingBoxIndex];
  86031. var min = boundingBox.minimum;
  86032. var max = boundingBox.maximum;
  86033. var diff = max.subtract(min);
  86034. var median = min.add(diff.scale(0.5));
  86035. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86036. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86037. .multiply(boundingBox.getWorldMatrix());
  86038. // VBOs
  86039. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86040. if (this.showBackLines) {
  86041. // Back
  86042. engine.setDepthFunctionToGreaterOrEqual();
  86043. this._scene.resetCachedMaterial();
  86044. this._colorShader.setColor4("color", this.backColor.toColor4());
  86045. this._colorShader.bind(worldMatrix);
  86046. // Draw order
  86047. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86048. }
  86049. // Front
  86050. engine.setDepthFunctionToLess();
  86051. this._scene.resetCachedMaterial();
  86052. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86053. this._colorShader.bind(worldMatrix);
  86054. // Draw order
  86055. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86056. }
  86057. this._colorShader.unbind();
  86058. engine.setDepthFunctionToLessOrEqual();
  86059. engine.setDepthWrite(true);
  86060. };
  86061. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86062. this._prepareRessources();
  86063. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86064. return;
  86065. }
  86066. var engine = this._scene.getEngine();
  86067. engine.setDepthWrite(false);
  86068. engine.setColorWrite(false);
  86069. this._colorShader._preBind();
  86070. var boundingBox = mesh._boundingInfo.boundingBox;
  86071. var min = boundingBox.minimum;
  86072. var max = boundingBox.maximum;
  86073. var diff = max.subtract(min);
  86074. var median = min.add(diff.scale(0.5));
  86075. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86076. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86077. .multiply(boundingBox.getWorldMatrix());
  86078. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86079. engine.setDepthFunctionToLess();
  86080. this._scene.resetCachedMaterial();
  86081. this._colorShader.bind(worldMatrix);
  86082. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86083. this._colorShader.unbind();
  86084. engine.setDepthFunctionToLessOrEqual();
  86085. engine.setDepthWrite(true);
  86086. engine.setColorWrite(true);
  86087. };
  86088. BoundingBoxRenderer.prototype.dispose = function () {
  86089. if (!this._colorShader) {
  86090. return;
  86091. }
  86092. this.renderList.dispose();
  86093. this._colorShader.dispose();
  86094. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86095. if (buffer) {
  86096. buffer.dispose();
  86097. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86098. }
  86099. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86100. };
  86101. return BoundingBoxRenderer;
  86102. }());
  86103. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86104. })(BABYLON || (BABYLON = {}));
  86105. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86106. var BABYLON;
  86107. (function (BABYLON) {
  86108. /**
  86109. * Renders a layer on top of an existing scene
  86110. */
  86111. var UtilityLayerRenderer = /** @class */ (function () {
  86112. /**
  86113. * Instantiates a UtilityLayerRenderer
  86114. * @param originalScene the original scene that will be rendered on top of
  86115. */
  86116. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86117. var _this = this;
  86118. this.originalScene = originalScene;
  86119. /**
  86120. * If the utility layer should automatically be rendered on top of existing scene
  86121. */
  86122. this.shouldRender = true;
  86123. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86124. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86125. originalScene.getEngine().scenes.pop();
  86126. // Render directly on top of existing scene without clearing
  86127. this.utilityLayerScene.autoClear = false;
  86128. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  86129. if (_this.shouldRender) {
  86130. _this.render();
  86131. }
  86132. });
  86133. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  86134. _this.dispose();
  86135. });
  86136. }
  86137. /**
  86138. * Renders the utility layers scene on top of the original scene
  86139. */
  86140. UtilityLayerRenderer.prototype.render = function () {
  86141. this._updateCamera();
  86142. this.utilityLayerScene.render(false);
  86143. };
  86144. /**
  86145. * Disposes of the renderer
  86146. */
  86147. UtilityLayerRenderer.prototype.dispose = function () {
  86148. if (this._afterRenderObserver) {
  86149. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  86150. }
  86151. if (this._sceneDisposeObserver) {
  86152. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86153. }
  86154. this.utilityLayerScene.dispose();
  86155. };
  86156. UtilityLayerRenderer.prototype._updateCamera = function () {
  86157. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  86158. };
  86159. return UtilityLayerRenderer;
  86160. }());
  86161. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  86162. })(BABYLON || (BABYLON = {}));
  86163. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  86164. var BABYLON;
  86165. (function (BABYLON) {
  86166. /**
  86167. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  86168. */
  86169. var Gizmo = /** @class */ (function () {
  86170. /**
  86171. * Creates a gizmo
  86172. * @param gizmoLayer The utility layer the gizmo will be added to
  86173. */
  86174. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  86175. var _this = this;
  86176. this.gizmoLayer = gizmoLayer;
  86177. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  86178. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  86179. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  86180. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 5;
  86181. _this._rootMesh.scaling.set(dist, dist, dist);
  86182. }
  86183. if (_this.attachedMesh) {
  86184. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  86185. }
  86186. });
  86187. }
  86188. /**
  86189. * Disposes of the gizmo
  86190. */
  86191. Gizmo.prototype.dispose = function () {
  86192. this._rootMesh.dispose();
  86193. if (this._beforeRenderObserver) {
  86194. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  86195. }
  86196. };
  86197. return Gizmo;
  86198. }());
  86199. BABYLON.Gizmo = Gizmo;
  86200. })(BABYLON || (BABYLON = {}));
  86201. //# sourceMappingURL=babylon.gizmo.js.map
  86202. var BABYLON;
  86203. (function (BABYLON) {
  86204. /**
  86205. * Single axis drag gizmo
  86206. */
  86207. var AxisDragGizmo = /** @class */ (function (_super) {
  86208. __extends(AxisDragGizmo, _super);
  86209. /**
  86210. * Creates an AxisDragGizmo
  86211. * @param gizmoLayer The utility layer the gizmo will be added to
  86212. * @param dragAxis The axis which the gizmo will be able to drag on
  86213. * @param color The color of the gizmo
  86214. */
  86215. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  86216. var _this = _super.call(this, gizmoLayer) || this;
  86217. // Create Material
  86218. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86219. coloredMaterial.disableLighting = true;
  86220. coloredMaterial.emissiveColor = color;
  86221. // Build mesh on root node
  86222. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86223. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86224. _this._rootMesh.addChild(arrowMesh);
  86225. _this._rootMesh.addChild(arrowTail);
  86226. // Position arrow pointing in its drag axis
  86227. arrowMesh.scaling.scaleInPlace(0.1);
  86228. arrowMesh.material = coloredMaterial;
  86229. arrowMesh.rotation.x = Math.PI / 2;
  86230. arrowMesh.position.z += 0.3;
  86231. arrowTail.rotation.x = Math.PI / 2;
  86232. arrowTail.material = coloredMaterial;
  86233. arrowTail.position.z += 0.2;
  86234. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  86235. // Add drag behavior to handle events when the gizmo is dragged
  86236. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis, pointerObservableScene: gizmoLayer.originalScene });
  86237. _this._dragBehavior.moveAttached = false;
  86238. _this._rootMesh.addBehavior(_this._dragBehavior);
  86239. _this._dragBehavior.onDragObservable.add(function (event) {
  86240. if (_this.attachedMesh) {
  86241. _this.attachedMesh.position.addInPlace(event.delta);
  86242. }
  86243. });
  86244. return _this;
  86245. }
  86246. /**
  86247. * Disposes of the gizmo
  86248. */
  86249. AxisDragGizmo.prototype.dispose = function () {
  86250. this._dragBehavior.detach();
  86251. _super.prototype.dispose.call(this);
  86252. };
  86253. return AxisDragGizmo;
  86254. }(BABYLON.Gizmo));
  86255. BABYLON.AxisDragGizmo = AxisDragGizmo;
  86256. })(BABYLON || (BABYLON = {}));
  86257. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  86258. var BABYLON;
  86259. (function (BABYLON) {
  86260. /**
  86261. * Gizmo that enables dragging a mesh along 3 axis
  86262. */
  86263. var PositionGizmo = /** @class */ (function (_super) {
  86264. __extends(PositionGizmo, _super);
  86265. /**
  86266. * Creates a PositionGizmo
  86267. * @param gizmoLayer The utility layer the gizmo will be added to
  86268. */
  86269. function PositionGizmo(gizmoLayer) {
  86270. var _this = _super.call(this, gizmoLayer) || this;
  86271. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86272. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86273. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86274. return _this;
  86275. }
  86276. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  86277. set: function (mesh) {
  86278. this._xDrag.attachedMesh = mesh;
  86279. this._yDrag.attachedMesh = mesh;
  86280. this._zDrag.attachedMesh = mesh;
  86281. },
  86282. enumerable: true,
  86283. configurable: true
  86284. });
  86285. /**
  86286. * Disposes of the gizmo
  86287. */
  86288. PositionGizmo.prototype.dispose = function () {
  86289. this._xDrag.dispose();
  86290. this._yDrag.dispose();
  86291. this._zDrag.dispose();
  86292. };
  86293. return PositionGizmo;
  86294. }(BABYLON.Gizmo));
  86295. BABYLON.PositionGizmo = PositionGizmo;
  86296. })(BABYLON || (BABYLON = {}));
  86297. //# sourceMappingURL=babylon.positionGizmo.js.map
  86298. var BABYLON;
  86299. (function (BABYLON) {
  86300. /**
  86301. * Defines a target to use with MorphTargetManager
  86302. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86303. */
  86304. var MorphTarget = /** @class */ (function () {
  86305. /**
  86306. * Creates a new MorphTarget
  86307. * @param name defines the name of the target
  86308. * @param influence defines the influence to use
  86309. */
  86310. function MorphTarget(
  86311. /** defines the name of the target */
  86312. name, influence, scene) {
  86313. if (influence === void 0) { influence = 0; }
  86314. if (scene === void 0) { scene = null; }
  86315. this.name = name;
  86316. /**
  86317. * Gets or sets the list of animations
  86318. */
  86319. this.animations = new Array();
  86320. this._positions = null;
  86321. this._normals = null;
  86322. this._tangents = null;
  86323. /**
  86324. * Observable raised when the influence changes
  86325. */
  86326. this.onInfluenceChanged = new BABYLON.Observable();
  86327. this._animationPropertiesOverride = null;
  86328. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86329. this.influence = influence;
  86330. }
  86331. Object.defineProperty(MorphTarget.prototype, "influence", {
  86332. /**
  86333. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  86334. */
  86335. get: function () {
  86336. return this._influence;
  86337. },
  86338. set: function (influence) {
  86339. if (this._influence === influence) {
  86340. return;
  86341. }
  86342. var previous = this._influence;
  86343. this._influence = influence;
  86344. if (this.onInfluenceChanged.hasObservers) {
  86345. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  86346. }
  86347. },
  86348. enumerable: true,
  86349. configurable: true
  86350. });
  86351. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  86352. /**
  86353. * Gets or sets the animation properties override
  86354. */
  86355. get: function () {
  86356. if (!this._animationPropertiesOverride && this._scene) {
  86357. return this._scene.animationPropertiesOverride;
  86358. }
  86359. return this._animationPropertiesOverride;
  86360. },
  86361. set: function (value) {
  86362. this._animationPropertiesOverride = value;
  86363. },
  86364. enumerable: true,
  86365. configurable: true
  86366. });
  86367. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  86368. /**
  86369. * Gets a boolean defining if the target contains position data
  86370. */
  86371. get: function () {
  86372. return !!this._positions;
  86373. },
  86374. enumerable: true,
  86375. configurable: true
  86376. });
  86377. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  86378. /**
  86379. * Gets a boolean defining if the target contains normal data
  86380. */
  86381. get: function () {
  86382. return !!this._normals;
  86383. },
  86384. enumerable: true,
  86385. configurable: true
  86386. });
  86387. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  86388. /**
  86389. * Gets a boolean defining if the target contains tangent data
  86390. */
  86391. get: function () {
  86392. return !!this._tangents;
  86393. },
  86394. enumerable: true,
  86395. configurable: true
  86396. });
  86397. /**
  86398. * Affects position data to this target
  86399. * @param data defines the position data to use
  86400. */
  86401. MorphTarget.prototype.setPositions = function (data) {
  86402. this._positions = data;
  86403. };
  86404. /**
  86405. * Gets the position data stored in this target
  86406. * @returns a FloatArray containing the position data (or null if not present)
  86407. */
  86408. MorphTarget.prototype.getPositions = function () {
  86409. return this._positions;
  86410. };
  86411. /**
  86412. * Affects normal data to this target
  86413. * @param data defines the normal data to use
  86414. */
  86415. MorphTarget.prototype.setNormals = function (data) {
  86416. this._normals = data;
  86417. };
  86418. /**
  86419. * Gets the normal data stored in this target
  86420. * @returns a FloatArray containing the normal data (or null if not present)
  86421. */
  86422. MorphTarget.prototype.getNormals = function () {
  86423. return this._normals;
  86424. };
  86425. /**
  86426. * Affects tangent data to this target
  86427. * @param data defines the tangent data to use
  86428. */
  86429. MorphTarget.prototype.setTangents = function (data) {
  86430. this._tangents = data;
  86431. };
  86432. /**
  86433. * Gets the tangent data stored in this target
  86434. * @returns a FloatArray containing the tangent data (or null if not present)
  86435. */
  86436. MorphTarget.prototype.getTangents = function () {
  86437. return this._tangents;
  86438. };
  86439. /**
  86440. * Serializes the current target into a Serialization object
  86441. * @returns the serialized object
  86442. */
  86443. MorphTarget.prototype.serialize = function () {
  86444. var serializationObject = {};
  86445. serializationObject.name = this.name;
  86446. serializationObject.influence = this.influence;
  86447. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  86448. if (this.hasNormals) {
  86449. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  86450. }
  86451. if (this.hasTangents) {
  86452. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  86453. }
  86454. // Animations
  86455. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  86456. return serializationObject;
  86457. };
  86458. // Statics
  86459. /**
  86460. * Creates a new target from serialized data
  86461. * @param serializationObject defines the serialized data to use
  86462. * @returns a new MorphTarget
  86463. */
  86464. MorphTarget.Parse = function (serializationObject) {
  86465. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  86466. result.setPositions(serializationObject.positions);
  86467. if (serializationObject.normals) {
  86468. result.setNormals(serializationObject.normals);
  86469. }
  86470. if (serializationObject.tangents) {
  86471. result.setTangents(serializationObject.tangents);
  86472. }
  86473. // Animations
  86474. if (serializationObject.animations) {
  86475. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  86476. var parsedAnimation = serializationObject.animations[animationIndex];
  86477. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  86478. }
  86479. }
  86480. return result;
  86481. };
  86482. /**
  86483. * Creates a MorphTarget from mesh data
  86484. * @param mesh defines the source mesh
  86485. * @param name defines the name to use for the new target
  86486. * @param influence defines the influence to attach to the target
  86487. * @returns a new MorphTarget
  86488. */
  86489. MorphTarget.FromMesh = function (mesh, name, influence) {
  86490. if (!name) {
  86491. name = mesh.name;
  86492. }
  86493. var result = new MorphTarget(name, influence, mesh.getScene());
  86494. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86495. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86496. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  86497. }
  86498. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  86499. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  86500. }
  86501. return result;
  86502. };
  86503. return MorphTarget;
  86504. }());
  86505. BABYLON.MorphTarget = MorphTarget;
  86506. })(BABYLON || (BABYLON = {}));
  86507. //# sourceMappingURL=babylon.morphTarget.js.map
  86508. var BABYLON;
  86509. (function (BABYLON) {
  86510. /**
  86511. * This class is used to deform meshes using morphing between different targets
  86512. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86513. */
  86514. var MorphTargetManager = /** @class */ (function () {
  86515. /**
  86516. * Creates a new MorphTargetManager
  86517. * @param scene defines the current scene
  86518. */
  86519. function MorphTargetManager(scene) {
  86520. if (scene === void 0) { scene = null; }
  86521. this._targets = new Array();
  86522. this._targetObservable = new Array();
  86523. this._activeTargets = new BABYLON.SmartArray(16);
  86524. this._supportsNormals = false;
  86525. this._supportsTangents = false;
  86526. this._vertexCount = 0;
  86527. this._uniqueId = 0;
  86528. this._tempInfluences = new Array();
  86529. if (!scene) {
  86530. scene = BABYLON.Engine.LastCreatedScene;
  86531. }
  86532. this._scene = scene;
  86533. if (this._scene) {
  86534. this._scene.morphTargetManagers.push(this);
  86535. this._uniqueId = this._scene.getUniqueId();
  86536. }
  86537. }
  86538. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86539. /**
  86540. * Gets the unique ID of this manager
  86541. */
  86542. get: function () {
  86543. return this._uniqueId;
  86544. },
  86545. enumerable: true,
  86546. configurable: true
  86547. });
  86548. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86549. /**
  86550. * Gets the number of vertices handled by this manager
  86551. */
  86552. get: function () {
  86553. return this._vertexCount;
  86554. },
  86555. enumerable: true,
  86556. configurable: true
  86557. });
  86558. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86559. /**
  86560. * Gets a boolean indicating if this manager supports morphing of normals
  86561. */
  86562. get: function () {
  86563. return this._supportsNormals;
  86564. },
  86565. enumerable: true,
  86566. configurable: true
  86567. });
  86568. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86569. /**
  86570. * Gets a boolean indicating if this manager supports morphing of tangents
  86571. */
  86572. get: function () {
  86573. return this._supportsTangents;
  86574. },
  86575. enumerable: true,
  86576. configurable: true
  86577. });
  86578. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86579. /**
  86580. * Gets the number of targets stored in this manager
  86581. */
  86582. get: function () {
  86583. return this._targets.length;
  86584. },
  86585. enumerable: true,
  86586. configurable: true
  86587. });
  86588. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86589. /**
  86590. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86591. */
  86592. get: function () {
  86593. return this._activeTargets.length;
  86594. },
  86595. enumerable: true,
  86596. configurable: true
  86597. });
  86598. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86599. /**
  86600. * Gets the list of influences (one per target)
  86601. */
  86602. get: function () {
  86603. return this._influences;
  86604. },
  86605. enumerable: true,
  86606. configurable: true
  86607. });
  86608. /**
  86609. * Gets the active target at specified index. An active target is a target with an influence > 0
  86610. * @param index defines the index to check
  86611. * @returns the requested target
  86612. */
  86613. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86614. return this._activeTargets.data[index];
  86615. };
  86616. /**
  86617. * Gets the target at specified index
  86618. * @param index defines the index to check
  86619. * @returns the requested target
  86620. */
  86621. MorphTargetManager.prototype.getTarget = function (index) {
  86622. return this._targets[index];
  86623. };
  86624. /**
  86625. * Add a new target to this manager
  86626. * @param target defines the target to add
  86627. */
  86628. MorphTargetManager.prototype.addTarget = function (target) {
  86629. var _this = this;
  86630. this._targets.push(target);
  86631. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86632. _this._syncActiveTargets(needUpdate);
  86633. }));
  86634. this._syncActiveTargets(true);
  86635. };
  86636. /**
  86637. * Removes a target from the manager
  86638. * @param target defines the target to remove
  86639. */
  86640. MorphTargetManager.prototype.removeTarget = function (target) {
  86641. var index = this._targets.indexOf(target);
  86642. if (index >= 0) {
  86643. this._targets.splice(index, 1);
  86644. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86645. this._syncActiveTargets(true);
  86646. }
  86647. };
  86648. /**
  86649. * Serializes the current manager into a Serialization object
  86650. * @returns the serialized object
  86651. */
  86652. MorphTargetManager.prototype.serialize = function () {
  86653. var serializationObject = {};
  86654. serializationObject.id = this.uniqueId;
  86655. serializationObject.targets = [];
  86656. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86657. var target = _a[_i];
  86658. serializationObject.targets.push(target.serialize());
  86659. }
  86660. return serializationObject;
  86661. };
  86662. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86663. var influenceCount = 0;
  86664. this._activeTargets.reset();
  86665. this._supportsNormals = true;
  86666. this._supportsTangents = true;
  86667. this._vertexCount = 0;
  86668. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86669. var target = _a[_i];
  86670. this._activeTargets.push(target);
  86671. this._tempInfluences[influenceCount++] = target.influence;
  86672. var positions = target.getPositions();
  86673. if (positions) {
  86674. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86675. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86676. var vertexCount = positions.length / 3;
  86677. if (this._vertexCount === 0) {
  86678. this._vertexCount = vertexCount;
  86679. }
  86680. else if (this._vertexCount !== vertexCount) {
  86681. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86682. return;
  86683. }
  86684. }
  86685. }
  86686. if (!this._influences || this._influences.length !== influenceCount) {
  86687. this._influences = new Float32Array(influenceCount);
  86688. }
  86689. for (var index = 0; index < influenceCount; index++) {
  86690. this._influences[index] = this._tempInfluences[index];
  86691. }
  86692. if (needUpdate) {
  86693. this.synchronize();
  86694. }
  86695. };
  86696. /**
  86697. * Syncrhonize the targets with all the meshes using this morph target manager
  86698. */
  86699. MorphTargetManager.prototype.synchronize = function () {
  86700. if (!this._scene) {
  86701. return;
  86702. }
  86703. // Flag meshes as dirty to resync with the active targets
  86704. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86705. var mesh = _a[_i];
  86706. if (mesh.morphTargetManager === this) {
  86707. mesh._syncGeometryWithMorphTargetManager();
  86708. }
  86709. }
  86710. };
  86711. // Statics
  86712. /**
  86713. * Creates a new MorphTargetManager from serialized data
  86714. * @param serializationObject defines the serialized data
  86715. * @param scene defines the hosting scene
  86716. * @returns the new MorphTargetManager
  86717. */
  86718. MorphTargetManager.Parse = function (serializationObject, scene) {
  86719. var result = new MorphTargetManager(scene);
  86720. result._uniqueId = serializationObject.id;
  86721. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86722. var targetData = _a[_i];
  86723. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86724. }
  86725. return result;
  86726. };
  86727. return MorphTargetManager;
  86728. }());
  86729. BABYLON.MorphTargetManager = MorphTargetManager;
  86730. })(BABYLON || (BABYLON = {}));
  86731. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86732. var BABYLON;
  86733. (function (BABYLON) {
  86734. var Octree = /** @class */ (function () {
  86735. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86736. if (maxDepth === void 0) { maxDepth = 2; }
  86737. this.maxDepth = maxDepth;
  86738. this.dynamicContent = new Array();
  86739. this._maxBlockCapacity = maxBlockCapacity || 64;
  86740. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86741. this._creationFunc = creationFunc;
  86742. }
  86743. // Methods
  86744. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86745. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86746. };
  86747. Octree.prototype.addMesh = function (entry) {
  86748. for (var index = 0; index < this.blocks.length; index++) {
  86749. var block = this.blocks[index];
  86750. block.addEntry(entry);
  86751. }
  86752. };
  86753. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86754. this._selectionContent.reset();
  86755. for (var index = 0; index < this.blocks.length; index++) {
  86756. var block = this.blocks[index];
  86757. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86758. }
  86759. if (allowDuplicate) {
  86760. this._selectionContent.concat(this.dynamicContent);
  86761. }
  86762. else {
  86763. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86764. }
  86765. return this._selectionContent;
  86766. };
  86767. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86768. this._selectionContent.reset();
  86769. for (var index = 0; index < this.blocks.length; index++) {
  86770. var block = this.blocks[index];
  86771. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86772. }
  86773. if (allowDuplicate) {
  86774. this._selectionContent.concat(this.dynamicContent);
  86775. }
  86776. else {
  86777. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86778. }
  86779. return this._selectionContent;
  86780. };
  86781. Octree.prototype.intersectsRay = function (ray) {
  86782. this._selectionContent.reset();
  86783. for (var index = 0; index < this.blocks.length; index++) {
  86784. var block = this.blocks[index];
  86785. block.intersectsRay(ray, this._selectionContent);
  86786. }
  86787. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86788. return this._selectionContent;
  86789. };
  86790. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86791. target.blocks = new Array();
  86792. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86793. // Segmenting space
  86794. for (var x = 0; x < 2; x++) {
  86795. for (var y = 0; y < 2; y++) {
  86796. for (var z = 0; z < 2; z++) {
  86797. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86798. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86799. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86800. block.addEntries(entries);
  86801. target.blocks.push(block);
  86802. }
  86803. }
  86804. }
  86805. };
  86806. Octree.CreationFuncForMeshes = function (entry, block) {
  86807. var boundingInfo = entry.getBoundingInfo();
  86808. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86809. block.entries.push(entry);
  86810. }
  86811. };
  86812. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86813. var boundingInfo = entry.getBoundingInfo();
  86814. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86815. block.entries.push(entry);
  86816. }
  86817. };
  86818. return Octree;
  86819. }());
  86820. BABYLON.Octree = Octree;
  86821. })(BABYLON || (BABYLON = {}));
  86822. //# sourceMappingURL=babylon.octree.js.map
  86823. var BABYLON;
  86824. (function (BABYLON) {
  86825. var OctreeBlock = /** @class */ (function () {
  86826. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86827. this.entries = new Array();
  86828. this._boundingVectors = new Array();
  86829. this._capacity = capacity;
  86830. this._depth = depth;
  86831. this._maxDepth = maxDepth;
  86832. this._creationFunc = creationFunc;
  86833. this._minPoint = minPoint;
  86834. this._maxPoint = maxPoint;
  86835. this._boundingVectors.push(minPoint.clone());
  86836. this._boundingVectors.push(maxPoint.clone());
  86837. this._boundingVectors.push(minPoint.clone());
  86838. this._boundingVectors[2].x = maxPoint.x;
  86839. this._boundingVectors.push(minPoint.clone());
  86840. this._boundingVectors[3].y = maxPoint.y;
  86841. this._boundingVectors.push(minPoint.clone());
  86842. this._boundingVectors[4].z = maxPoint.z;
  86843. this._boundingVectors.push(maxPoint.clone());
  86844. this._boundingVectors[5].z = minPoint.z;
  86845. this._boundingVectors.push(maxPoint.clone());
  86846. this._boundingVectors[6].x = minPoint.x;
  86847. this._boundingVectors.push(maxPoint.clone());
  86848. this._boundingVectors[7].y = minPoint.y;
  86849. }
  86850. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86851. // Property
  86852. get: function () {
  86853. return this._capacity;
  86854. },
  86855. enumerable: true,
  86856. configurable: true
  86857. });
  86858. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86859. get: function () {
  86860. return this._minPoint;
  86861. },
  86862. enumerable: true,
  86863. configurable: true
  86864. });
  86865. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86866. get: function () {
  86867. return this._maxPoint;
  86868. },
  86869. enumerable: true,
  86870. configurable: true
  86871. });
  86872. // Methods
  86873. OctreeBlock.prototype.addEntry = function (entry) {
  86874. if (this.blocks) {
  86875. for (var index = 0; index < this.blocks.length; index++) {
  86876. var block = this.blocks[index];
  86877. block.addEntry(entry);
  86878. }
  86879. return;
  86880. }
  86881. this._creationFunc(entry, this);
  86882. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86883. this.createInnerBlocks();
  86884. }
  86885. };
  86886. OctreeBlock.prototype.addEntries = function (entries) {
  86887. for (var index = 0; index < entries.length; index++) {
  86888. var mesh = entries[index];
  86889. this.addEntry(mesh);
  86890. }
  86891. };
  86892. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86893. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86894. if (this.blocks) {
  86895. for (var index = 0; index < this.blocks.length; index++) {
  86896. var block = this.blocks[index];
  86897. block.select(frustumPlanes, selection, allowDuplicate);
  86898. }
  86899. return;
  86900. }
  86901. if (allowDuplicate) {
  86902. selection.concat(this.entries);
  86903. }
  86904. else {
  86905. selection.concatWithNoDuplicate(this.entries);
  86906. }
  86907. }
  86908. };
  86909. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86910. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86911. if (this.blocks) {
  86912. for (var index = 0; index < this.blocks.length; index++) {
  86913. var block = this.blocks[index];
  86914. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86915. }
  86916. return;
  86917. }
  86918. if (allowDuplicate) {
  86919. selection.concat(this.entries);
  86920. }
  86921. else {
  86922. selection.concatWithNoDuplicate(this.entries);
  86923. }
  86924. }
  86925. };
  86926. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86927. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86928. if (this.blocks) {
  86929. for (var index = 0; index < this.blocks.length; index++) {
  86930. var block = this.blocks[index];
  86931. block.intersectsRay(ray, selection);
  86932. }
  86933. return;
  86934. }
  86935. selection.concatWithNoDuplicate(this.entries);
  86936. }
  86937. };
  86938. OctreeBlock.prototype.createInnerBlocks = function () {
  86939. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86940. };
  86941. return OctreeBlock;
  86942. }());
  86943. BABYLON.OctreeBlock = OctreeBlock;
  86944. })(BABYLON || (BABYLON = {}));
  86945. //# sourceMappingURL=babylon.octreeBlock.js.map
  86946. var BABYLON;
  86947. (function (BABYLON) {
  86948. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86949. __extends(VRDistortionCorrectionPostProcess, _super);
  86950. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86951. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86952. 'LensCenter',
  86953. 'Scale',
  86954. 'ScaleIn',
  86955. 'HmdWarpParam'
  86956. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86957. _this._isRightEye = isRightEye;
  86958. _this._distortionFactors = vrMetrics.distortionK;
  86959. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86960. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86961. _this.adaptScaleToCurrentViewport = true;
  86962. _this.onSizeChangedObservable.add(function () {
  86963. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86964. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86965. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86966. });
  86967. _this.onApplyObservable.add(function (effect) {
  86968. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86969. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86970. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86971. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86972. });
  86973. return _this;
  86974. }
  86975. return VRDistortionCorrectionPostProcess;
  86976. }(BABYLON.PostProcess));
  86977. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86978. })(BABYLON || (BABYLON = {}));
  86979. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86980. var BABYLON;
  86981. (function (BABYLON) {
  86982. /**
  86983. * Postprocess used to generate anaglyphic rendering
  86984. */
  86985. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86986. __extends(AnaglyphPostProcess, _super);
  86987. /**
  86988. * Creates a new AnaglyphPostProcess
  86989. * @param name defines postprocess name
  86990. * @param options defines creation options or target ratio scale
  86991. * @param rigCameras defines cameras using this postprocess
  86992. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86993. * @param engine defines hosting engine
  86994. * @param reusable defines if the postprocess will be reused multiple times per frame
  86995. */
  86996. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86997. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86998. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86999. _this.onApplyObservable.add(function (effect) {
  87000. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  87001. });
  87002. return _this;
  87003. }
  87004. return AnaglyphPostProcess;
  87005. }(BABYLON.PostProcess));
  87006. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  87007. })(BABYLON || (BABYLON = {}));
  87008. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  87009. var BABYLON;
  87010. (function (BABYLON) {
  87011. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  87012. __extends(StereoscopicInterlacePostProcess, _super);
  87013. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  87014. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  87015. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87016. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87017. _this.onSizeChangedObservable.add(function () {
  87018. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87019. });
  87020. _this.onApplyObservable.add(function (effect) {
  87021. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  87022. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  87023. });
  87024. return _this;
  87025. }
  87026. return StereoscopicInterlacePostProcess;
  87027. }(BABYLON.PostProcess));
  87028. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  87029. })(BABYLON || (BABYLON = {}));
  87030. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  87031. var BABYLON;
  87032. (function (BABYLON) {
  87033. /**
  87034. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  87035. * Screen rotation is taken into account.
  87036. */
  87037. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  87038. function FreeCameraDeviceOrientationInput() {
  87039. var _this = this;
  87040. this._screenOrientationAngle = 0;
  87041. this._screenQuaternion = new BABYLON.Quaternion();
  87042. this._alpha = 0;
  87043. this._beta = 0;
  87044. this._gamma = 0;
  87045. this._orientationChanged = function () {
  87046. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  87047. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  87048. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  87049. };
  87050. this._deviceOrientation = function (evt) {
  87051. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  87052. _this._beta = evt.beta !== null ? evt.beta : 0;
  87053. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  87054. };
  87055. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  87056. this._orientationChanged();
  87057. }
  87058. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  87059. get: function () {
  87060. return this._camera;
  87061. },
  87062. set: function (camera) {
  87063. this._camera = camera;
  87064. if (this._camera != null && !this._camera.rotationQuaternion) {
  87065. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  87066. }
  87067. },
  87068. enumerable: true,
  87069. configurable: true
  87070. });
  87071. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87072. window.addEventListener("orientationchange", this._orientationChanged);
  87073. window.addEventListener("deviceorientation", this._deviceOrientation);
  87074. //In certain cases, the attach control is called AFTER orientation was changed,
  87075. //So this is needed.
  87076. this._orientationChanged();
  87077. };
  87078. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  87079. window.removeEventListener("orientationchange", this._orientationChanged);
  87080. window.removeEventListener("deviceorientation", this._deviceOrientation);
  87081. };
  87082. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  87083. //if no device orientation provided, don't update the rotation.
  87084. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  87085. if (!this._alpha)
  87086. return;
  87087. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  87088. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  87089. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  87090. //Mirror on XY Plane
  87091. this._camera.rotationQuaternion.z *= -1;
  87092. this._camera.rotationQuaternion.w *= -1;
  87093. };
  87094. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  87095. return "FreeCameraDeviceOrientationInput";
  87096. };
  87097. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  87098. return "deviceOrientation";
  87099. };
  87100. return FreeCameraDeviceOrientationInput;
  87101. }());
  87102. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  87103. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  87104. })(BABYLON || (BABYLON = {}));
  87105. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  87106. var BABYLON;
  87107. (function (BABYLON) {
  87108. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  87109. function ArcRotateCameraVRDeviceOrientationInput() {
  87110. this.alphaCorrection = 1;
  87111. this.betaCorrection = 1;
  87112. this.gammaCorrection = 1;
  87113. this._alpha = 0;
  87114. this._gamma = 0;
  87115. this._dirty = false;
  87116. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  87117. }
  87118. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87119. this.camera.attachControl(element, noPreventDefault);
  87120. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  87121. };
  87122. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  87123. if (evt.alpha !== null) {
  87124. this._alpha = +evt.alpha | 0;
  87125. }
  87126. if (evt.gamma !== null) {
  87127. this._gamma = +evt.gamma | 0;
  87128. }
  87129. this._dirty = true;
  87130. };
  87131. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  87132. if (this._dirty) {
  87133. this._dirty = false;
  87134. if (this._gamma < 0) {
  87135. this._gamma = 180 + this._gamma;
  87136. }
  87137. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  87138. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  87139. }
  87140. };
  87141. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  87142. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  87143. };
  87144. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  87145. return "ArcRotateCameraVRDeviceOrientationInput";
  87146. };
  87147. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  87148. return "VRDeviceOrientation";
  87149. };
  87150. return ArcRotateCameraVRDeviceOrientationInput;
  87151. }());
  87152. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  87153. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  87154. })(BABYLON || (BABYLON = {}));
  87155. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  87156. var BABYLON;
  87157. (function (BABYLON) {
  87158. var VRCameraMetrics = /** @class */ (function () {
  87159. function VRCameraMetrics() {
  87160. this.compensateDistortion = true;
  87161. }
  87162. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  87163. get: function () {
  87164. return this.hResolution / (2 * this.vResolution);
  87165. },
  87166. enumerable: true,
  87167. configurable: true
  87168. });
  87169. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  87170. get: function () {
  87171. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  87172. },
  87173. enumerable: true,
  87174. configurable: true
  87175. });
  87176. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  87177. get: function () {
  87178. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87179. var h = (4 * meters) / this.hScreenSize;
  87180. return BABYLON.Matrix.Translation(h, 0, 0);
  87181. },
  87182. enumerable: true,
  87183. configurable: true
  87184. });
  87185. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  87186. get: function () {
  87187. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87188. var h = (4 * meters) / this.hScreenSize;
  87189. return BABYLON.Matrix.Translation(-h, 0, 0);
  87190. },
  87191. enumerable: true,
  87192. configurable: true
  87193. });
  87194. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  87195. get: function () {
  87196. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  87197. },
  87198. enumerable: true,
  87199. configurable: true
  87200. });
  87201. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  87202. get: function () {
  87203. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  87204. },
  87205. enumerable: true,
  87206. configurable: true
  87207. });
  87208. VRCameraMetrics.GetDefault = function () {
  87209. var result = new VRCameraMetrics();
  87210. result.hResolution = 1280;
  87211. result.vResolution = 800;
  87212. result.hScreenSize = 0.149759993;
  87213. result.vScreenSize = 0.0935999975;
  87214. result.vScreenCenter = 0.0467999987;
  87215. result.eyeToScreenDistance = 0.0410000011;
  87216. result.lensSeparationDistance = 0.0635000020;
  87217. result.interpupillaryDistance = 0.0640000030;
  87218. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  87219. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  87220. result.postProcessScaleFactor = 1.714605507808412;
  87221. result.lensCenterOffset = 0.151976421;
  87222. return result;
  87223. };
  87224. return VRCameraMetrics;
  87225. }());
  87226. BABYLON.VRCameraMetrics = VRCameraMetrics;
  87227. })(BABYLON || (BABYLON = {}));
  87228. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  87229. var BABYLON;
  87230. (function (BABYLON) {
  87231. /**
  87232. * This represents a WebVR camera.
  87233. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  87234. * @example http://doc.babylonjs.com/how_to/webvr_camera
  87235. */
  87236. var WebVRFreeCamera = /** @class */ (function (_super) {
  87237. __extends(WebVRFreeCamera, _super);
  87238. /**
  87239. * Instantiates a WebVRFreeCamera.
  87240. * @param name The name of the WebVRFreeCamera
  87241. * @param position The starting anchor position for the camera
  87242. * @param scene The scene the camera belongs to
  87243. * @param webVROptions a set of customizable options for the webVRCamera
  87244. */
  87245. function WebVRFreeCamera(name, position, scene, webVROptions) {
  87246. if (webVROptions === void 0) { webVROptions = {}; }
  87247. var _this = _super.call(this, name, position, scene) || this;
  87248. _this.webVROptions = webVROptions;
  87249. /**
  87250. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  87251. */
  87252. _this._vrDevice = null;
  87253. /**
  87254. * The rawPose of the vrDevice.
  87255. */
  87256. _this.rawPose = null;
  87257. _this._specsVersion = "1.1";
  87258. _this._attached = false;
  87259. _this._descendants = [];
  87260. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  87261. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  87262. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  87263. _this._standingMatrix = null;
  87264. /**
  87265. * Represents device position in babylon space.
  87266. */
  87267. _this.devicePosition = BABYLON.Vector3.Zero();
  87268. /**
  87269. * Represents device rotation in babylon space.
  87270. */
  87271. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  87272. /**
  87273. * The scale of the device to be used when translating from device space to babylon space.
  87274. */
  87275. _this.deviceScaleFactor = 1;
  87276. _this._deviceToWorld = BABYLON.Matrix.Identity();
  87277. _this._worldToDevice = BABYLON.Matrix.Identity();
  87278. /**
  87279. * References to the webVR controllers for the vrDevice.
  87280. */
  87281. _this.controllers = [];
  87282. /**
  87283. * Emits an event when a controller is attached.
  87284. */
  87285. _this.onControllersAttachedObservable = new BABYLON.Observable();
  87286. /**
  87287. * Emits an event when a controller's mesh has been loaded;
  87288. */
  87289. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87290. /**
  87291. * If the rig cameras be used as parent instead of this camera.
  87292. */
  87293. _this.rigParenting = true;
  87294. _this._defaultHeight = undefined;
  87295. _this._workingVector = BABYLON.Vector3.Zero();
  87296. _this._oneVector = BABYLON.Vector3.One();
  87297. _this._workingMatrix = BABYLON.Matrix.Identity();
  87298. _this._cache.position = BABYLON.Vector3.Zero();
  87299. if (webVROptions.defaultHeight) {
  87300. _this._defaultHeight = webVROptions.defaultHeight;
  87301. _this.position.y = _this._defaultHeight;
  87302. }
  87303. _this.minZ = 0.1;
  87304. //legacy support - the compensation boolean was removed.
  87305. if (arguments.length === 5) {
  87306. _this.webVROptions = arguments[4];
  87307. }
  87308. // default webVR options
  87309. if (_this.webVROptions.trackPosition == undefined) {
  87310. _this.webVROptions.trackPosition = true;
  87311. }
  87312. if (_this.webVROptions.controllerMeshes == undefined) {
  87313. _this.webVROptions.controllerMeshes = true;
  87314. }
  87315. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  87316. _this.webVROptions.defaultLightingOnControllers = true;
  87317. }
  87318. _this.rotationQuaternion = new BABYLON.Quaternion();
  87319. if (_this.webVROptions && _this.webVROptions.positionScale) {
  87320. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  87321. }
  87322. //enable VR
  87323. var engine = _this.getEngine();
  87324. _this._onVREnabled = function (success) { if (success) {
  87325. _this.initControllers();
  87326. } };
  87327. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  87328. engine.initWebVR().add(function (event) {
  87329. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  87330. return;
  87331. }
  87332. _this._vrDevice = event.vrDisplay;
  87333. //reset the rig parameters.
  87334. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  87335. if (_this._attached) {
  87336. _this.getEngine().enableVR();
  87337. }
  87338. });
  87339. if (typeof (VRFrameData) !== "undefined")
  87340. _this._frameData = new VRFrameData();
  87341. /**
  87342. * The idea behind the following lines:
  87343. * objects that have the camera as parent should actually have the rig cameras as a parent.
  87344. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  87345. * the second will not show it correctly.
  87346. *
  87347. * To solve this - each object that has the camera as parent will be added to a protected array.
  87348. * When the rig camera renders, it will take this array and set all of those to be its children.
  87349. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  87350. * Amazing!
  87351. */
  87352. scene.onBeforeCameraRenderObservable.add(function (camera) {
  87353. if (camera.parent === _this && _this.rigParenting) {
  87354. _this._descendants = _this.getDescendants(true, function (n) {
  87355. // don't take the cameras or the controllers!
  87356. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  87357. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  87358. return !isController && !isRigCamera;
  87359. });
  87360. _this._descendants.forEach(function (node) {
  87361. node.parent = camera;
  87362. });
  87363. }
  87364. });
  87365. scene.onAfterCameraRenderObservable.add(function (camera) {
  87366. if (camera.parent === _this && _this.rigParenting) {
  87367. _this._descendants.forEach(function (node) {
  87368. node.parent = _this;
  87369. });
  87370. }
  87371. });
  87372. return _this;
  87373. }
  87374. /**
  87375. * Gets the device distance from the ground in meters.
  87376. * @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.
  87377. */
  87378. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  87379. if (this._standingMatrix) {
  87380. // Add standing matrix offset to get real offset from ground in room
  87381. this._standingMatrix.getTranslationToRef(this._workingVector);
  87382. return this._deviceRoomPosition.y + this._workingVector.y;
  87383. }
  87384. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  87385. return this._defaultHeight || 0;
  87386. };
  87387. /**
  87388. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87389. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  87390. */
  87391. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  87392. var _this = this;
  87393. if (callback === void 0) { callback = function (bool) { }; }
  87394. // Use standing matrix if available
  87395. this.getEngine().initWebVRAsync().then(function (result) {
  87396. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  87397. callback(false);
  87398. }
  87399. else {
  87400. _this._standingMatrix = new BABYLON.Matrix();
  87401. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  87402. if (!_this.getScene().useRightHandedSystem) {
  87403. [2, 6, 8, 9, 14].forEach(function (num) {
  87404. if (_this._standingMatrix) {
  87405. _this._standingMatrix.m[num] *= -1;
  87406. }
  87407. });
  87408. }
  87409. callback(true);
  87410. }
  87411. });
  87412. };
  87413. /**
  87414. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87415. * @returns A promise with a boolean set to if the standing matrix is supported.
  87416. */
  87417. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  87418. var _this = this;
  87419. return new Promise(function (res, rej) {
  87420. _this.useStandingMatrix(function (supported) {
  87421. res(supported);
  87422. });
  87423. });
  87424. };
  87425. /**
  87426. * Disposes the camera
  87427. */
  87428. WebVRFreeCamera.prototype.dispose = function () {
  87429. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  87430. _super.prototype.dispose.call(this);
  87431. };
  87432. /**
  87433. * Gets a vrController by name.
  87434. * @param name The name of the controller to retreive
  87435. * @returns the controller matching the name specified or null if not found
  87436. */
  87437. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  87438. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  87439. var gp = _a[_i];
  87440. if (gp.hand === name) {
  87441. return gp;
  87442. }
  87443. }
  87444. return null;
  87445. };
  87446. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  87447. /**
  87448. * The controller corrisponding to the users left hand.
  87449. */
  87450. get: function () {
  87451. if (!this._leftController) {
  87452. this._leftController = this.getControllerByName("left");
  87453. }
  87454. return this._leftController;
  87455. },
  87456. enumerable: true,
  87457. configurable: true
  87458. });
  87459. ;
  87460. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  87461. /**
  87462. * The controller corrisponding to the users right hand.
  87463. */
  87464. get: function () {
  87465. if (!this._rightController) {
  87466. this._rightController = this.getControllerByName("right");
  87467. }
  87468. return this._rightController;
  87469. },
  87470. enumerable: true,
  87471. configurable: true
  87472. });
  87473. ;
  87474. /**
  87475. * Casts a ray forward from the vrCamera's gaze.
  87476. * @param length Length of the ray (default: 100)
  87477. * @returns the ray corrisponding to the gaze
  87478. */
  87479. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  87480. if (length === void 0) { length = 100; }
  87481. if (this.leftCamera) {
  87482. // Use left eye to avoid computation to compute center on every call
  87483. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  87484. }
  87485. else {
  87486. return _super.prototype.getForwardRay.call(this, length);
  87487. }
  87488. };
  87489. /**
  87490. * Updates the camera based on device's frame data
  87491. */
  87492. WebVRFreeCamera.prototype._checkInputs = function () {
  87493. if (this._vrDevice && this._vrDevice.isPresenting) {
  87494. this._vrDevice.getFrameData(this._frameData);
  87495. this.updateFromDevice(this._frameData.pose);
  87496. }
  87497. _super.prototype._checkInputs.call(this);
  87498. };
  87499. /**
  87500. * Updates the poseControlled values based on the input device pose.
  87501. * @param poseData Pose coming from the device
  87502. */
  87503. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  87504. if (poseData && poseData.orientation) {
  87505. this.rawPose = poseData;
  87506. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  87507. if (this.getScene().useRightHandedSystem) {
  87508. this._deviceRoomRotationQuaternion.z *= -1;
  87509. this._deviceRoomRotationQuaternion.w *= -1;
  87510. }
  87511. if (this.webVROptions.trackPosition && this.rawPose.position) {
  87512. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  87513. if (this.getScene().useRightHandedSystem) {
  87514. this._deviceRoomPosition.z *= -1;
  87515. }
  87516. }
  87517. }
  87518. };
  87519. /**
  87520. * WebVR's attach control will start broadcasting frames to the device.
  87521. * Note that in certain browsers (chrome for example) this function must be called
  87522. * within a user-interaction callback. Example:
  87523. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87524. *
  87525. * @param element html element to attach the vrDevice to
  87526. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87527. */
  87528. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87529. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87530. this._attached = true;
  87531. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87532. if (this._vrDevice) {
  87533. this.getEngine().enableVR();
  87534. }
  87535. };
  87536. /**
  87537. * Detaches the camera from the html element and disables VR
  87538. *
  87539. * @param element html element to detach from
  87540. */
  87541. WebVRFreeCamera.prototype.detachControl = function (element) {
  87542. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87543. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87544. _super.prototype.detachControl.call(this, element);
  87545. this._attached = false;
  87546. this.getEngine().disableVR();
  87547. };
  87548. /**
  87549. * @returns the name of this class
  87550. */
  87551. WebVRFreeCamera.prototype.getClassName = function () {
  87552. return "WebVRFreeCamera";
  87553. };
  87554. /**
  87555. * Calls resetPose on the vrDisplay
  87556. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87557. */
  87558. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87559. //uses the vrDisplay's "resetPose()".
  87560. //pitch and roll won't be affected.
  87561. this._vrDevice.resetPose();
  87562. };
  87563. /**
  87564. * Updates the rig cameras (left and right eye)
  87565. */
  87566. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87567. var camLeft = this._rigCameras[0];
  87568. var camRight = this._rigCameras[1];
  87569. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87570. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87571. camLeft.position.copyFrom(this._deviceRoomPosition);
  87572. camRight.position.copyFrom(this._deviceRoomPosition);
  87573. };
  87574. /**
  87575. * Updates the cached values of the camera
  87576. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87577. */
  87578. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87579. var _this = this;
  87580. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87581. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87582. if (!this.updateCacheCalled) {
  87583. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87584. this.updateCacheCalled = true;
  87585. this.update();
  87586. }
  87587. // Set working vector to the device position in room space rotated by the new rotation
  87588. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87589. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87590. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87591. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87592. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87593. // Add translation from anchor position
  87594. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87595. this._workingVector.addInPlace(this.position);
  87596. this._workingVector.subtractInPlace(this._cache.position);
  87597. this._deviceToWorld.setTranslation(this._workingVector);
  87598. // Set an inverted matrix to be used when updating the camera
  87599. this._deviceToWorld.invertToRef(this._worldToDevice);
  87600. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87601. this.controllers.forEach(function (controller) {
  87602. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87603. controller.update();
  87604. });
  87605. }
  87606. if (!ignoreParentClass) {
  87607. _super.prototype._updateCache.call(this);
  87608. }
  87609. this.updateCacheCalled = false;
  87610. };
  87611. /**
  87612. * Updates the current device position and rotation in the babylon world
  87613. */
  87614. WebVRFreeCamera.prototype.update = function () {
  87615. // Get current device position in babylon world
  87616. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87617. // Get current device rotation in babylon world
  87618. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87619. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87620. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87621. _super.prototype.update.call(this);
  87622. };
  87623. /**
  87624. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87625. * @returns an identity matrix
  87626. */
  87627. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87628. return BABYLON.Matrix.Identity();
  87629. };
  87630. /**
  87631. * This function is called by the two RIG cameras.
  87632. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87633. */
  87634. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87635. var _this = this;
  87636. // Update the parent camera prior to using a child camera to avoid desynchronization
  87637. var parentCamera = this._cameraRigParams["parentCamera"];
  87638. parentCamera._updateCache();
  87639. //WebVR 1.1
  87640. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87641. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87642. if (!this.getScene().useRightHandedSystem) {
  87643. [2, 6, 8, 9, 14].forEach(function (num) {
  87644. _this._webvrViewMatrix.m[num] *= -1;
  87645. });
  87646. }
  87647. // update the camera rotation matrix
  87648. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87649. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87650. // Computing target and final matrix
  87651. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87652. // should the view matrix be updated with scale and position offset?
  87653. if (parentCamera.deviceScaleFactor !== 1) {
  87654. this._webvrViewMatrix.invert();
  87655. // scale the position, if set
  87656. if (parentCamera.deviceScaleFactor) {
  87657. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87658. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87659. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87660. }
  87661. this._webvrViewMatrix.invert();
  87662. }
  87663. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87664. // Compute global position
  87665. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87666. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87667. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87668. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87669. this._markSyncedWithParent();
  87670. return this._webvrViewMatrix;
  87671. };
  87672. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87673. var _this = this;
  87674. var parentCamera = this.parent;
  87675. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87676. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87677. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87678. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87679. //babylon compatible matrix
  87680. if (!this.getScene().useRightHandedSystem) {
  87681. [8, 9, 10, 11].forEach(function (num) {
  87682. _this._projectionMatrix.m[num] *= -1;
  87683. });
  87684. }
  87685. return this._projectionMatrix;
  87686. };
  87687. /**
  87688. * Initializes the controllers and their meshes
  87689. */
  87690. WebVRFreeCamera.prototype.initControllers = function () {
  87691. var _this = this;
  87692. this.controllers = [];
  87693. var manager = this.getScene().gamepadManager;
  87694. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87695. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87696. var webVrController = gamepad;
  87697. if (webVrController.defaultModel) {
  87698. webVrController.defaultModel.setEnabled(false);
  87699. }
  87700. if (webVrController.hand === "right") {
  87701. _this._rightController = null;
  87702. }
  87703. if (webVrController.hand === "left") {
  87704. _this._leftController = null;
  87705. }
  87706. var controllerIndex = _this.controllers.indexOf(webVrController);
  87707. if (controllerIndex !== -1) {
  87708. _this.controllers.splice(controllerIndex, 1);
  87709. }
  87710. }
  87711. });
  87712. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87713. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87714. var webVrController_1 = gamepad;
  87715. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87716. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87717. if (_this.webVROptions.controllerMeshes) {
  87718. if (webVrController_1.defaultModel) {
  87719. webVrController_1.defaultModel.setEnabled(true);
  87720. }
  87721. else {
  87722. // Load the meshes
  87723. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87724. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87725. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87726. if (_this.webVROptions.defaultLightingOnControllers) {
  87727. if (!_this._lightOnControllers) {
  87728. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87729. }
  87730. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87731. var children = mesh.getChildren();
  87732. if (children.length !== 0) {
  87733. children.forEach(function (mesh) {
  87734. light.includedOnlyMeshes.push(mesh);
  87735. activateLightOnSubMeshes_1(mesh, light);
  87736. });
  87737. }
  87738. };
  87739. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87740. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87741. }
  87742. });
  87743. }
  87744. }
  87745. webVrController_1.attachToPoseControlledCamera(_this);
  87746. // since this is async - sanity check. Is the controller already stored?
  87747. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87748. //add to the controllers array
  87749. _this.controllers.push(webVrController_1);
  87750. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87751. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87752. // So we're overriding setting left & right manually to be sure
  87753. var firstViveWandDetected = false;
  87754. for (var i = 0; i < _this.controllers.length; i++) {
  87755. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87756. if (!firstViveWandDetected) {
  87757. firstViveWandDetected = true;
  87758. _this.controllers[i].hand = "left";
  87759. }
  87760. else {
  87761. _this.controllers[i].hand = "right";
  87762. }
  87763. }
  87764. }
  87765. //did we find enough controllers? Great! let the developer know.
  87766. if (_this.controllers.length >= 2) {
  87767. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87768. }
  87769. }
  87770. }
  87771. });
  87772. };
  87773. return WebVRFreeCamera;
  87774. }(BABYLON.FreeCamera));
  87775. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87776. })(BABYLON || (BABYLON = {}));
  87777. //# sourceMappingURL=babylon.webVRCamera.js.map
  87778. var BABYLON;
  87779. (function (BABYLON) {
  87780. // We're mainly based on the logic defined into the FreeCamera code
  87781. /**
  87782. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87783. * being tilted forward or back and left or right.
  87784. */
  87785. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87786. __extends(DeviceOrientationCamera, _super);
  87787. /**
  87788. * Creates a new device orientation camera
  87789. * @param name The name of the camera
  87790. * @param position The start position camera
  87791. * @param scene The scene the camera belongs to
  87792. */
  87793. function DeviceOrientationCamera(name, position, scene) {
  87794. var _this = _super.call(this, name, position, scene) || this;
  87795. _this._quaternionCache = new BABYLON.Quaternion();
  87796. _this.inputs.addDeviceOrientation();
  87797. return _this;
  87798. }
  87799. /**
  87800. * Gets the current instance class name ("DeviceOrientationCamera").
  87801. * This helps avoiding instanceof at run time.
  87802. * @returns the class name
  87803. */
  87804. DeviceOrientationCamera.prototype.getClassName = function () {
  87805. return "DeviceOrientationCamera";
  87806. };
  87807. /**
  87808. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87809. */
  87810. DeviceOrientationCamera.prototype._checkInputs = function () {
  87811. _super.prototype._checkInputs.call(this);
  87812. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87813. if (this._initialQuaternion) {
  87814. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87815. }
  87816. };
  87817. /**
  87818. * Reset the camera to its default orientation on the specified axis only.
  87819. * @param axis The axis to reset
  87820. */
  87821. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87822. var _this = this;
  87823. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87824. //can only work if this camera has a rotation quaternion already.
  87825. if (!this.rotationQuaternion)
  87826. return;
  87827. if (!this._initialQuaternion) {
  87828. this._initialQuaternion = new BABYLON.Quaternion();
  87829. }
  87830. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87831. ['x', 'y', 'z'].forEach(function (axisName) {
  87832. if (!axis[axisName]) {
  87833. _this._initialQuaternion[axisName] = 0;
  87834. }
  87835. else {
  87836. _this._initialQuaternion[axisName] *= -1;
  87837. }
  87838. });
  87839. this._initialQuaternion.normalize();
  87840. //force rotation update
  87841. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87842. };
  87843. return DeviceOrientationCamera;
  87844. }(BABYLON.FreeCamera));
  87845. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87846. })(BABYLON || (BABYLON = {}));
  87847. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87848. var BABYLON;
  87849. (function (BABYLON) {
  87850. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87851. __extends(VRDeviceOrientationFreeCamera, _super);
  87852. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87853. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87854. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87855. var _this = _super.call(this, name, position, scene) || this;
  87856. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87857. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87858. return _this;
  87859. }
  87860. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87861. return "VRDeviceOrientationFreeCamera";
  87862. };
  87863. return VRDeviceOrientationFreeCamera;
  87864. }(BABYLON.DeviceOrientationCamera));
  87865. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87866. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87867. __extends(VRDeviceOrientationGamepadCamera, _super);
  87868. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87869. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87870. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87871. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87872. _this.inputs.addGamepad();
  87873. return _this;
  87874. }
  87875. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87876. return "VRDeviceOrientationGamepadCamera";
  87877. };
  87878. return VRDeviceOrientationGamepadCamera;
  87879. }(VRDeviceOrientationFreeCamera));
  87880. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87881. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87882. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87883. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87884. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87885. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87886. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87887. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87888. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87889. _this.inputs.addVRDeviceOrientation();
  87890. return _this;
  87891. }
  87892. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87893. return "VRDeviceOrientationArcRotateCamera";
  87894. };
  87895. return VRDeviceOrientationArcRotateCamera;
  87896. }(BABYLON.ArcRotateCamera));
  87897. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87898. })(BABYLON || (BABYLON = {}));
  87899. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87900. var BABYLON;
  87901. (function (BABYLON) {
  87902. /**
  87903. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87904. */
  87905. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87906. __extends(AnaglyphFreeCamera, _super);
  87907. /**
  87908. * Creates a new AnaglyphFreeCamera
  87909. * @param name defines camera name
  87910. * @param position defines initial position
  87911. * @param interaxialDistance defines distance between each color axis
  87912. * @param scene defines the hosting scene
  87913. */
  87914. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87915. var _this = _super.call(this, name, position, scene) || this;
  87916. _this.interaxialDistance = interaxialDistance;
  87917. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87918. return _this;
  87919. }
  87920. /**
  87921. * Gets camera class name
  87922. * @returns AnaglyphFreeCamera
  87923. */
  87924. AnaglyphFreeCamera.prototype.getClassName = function () {
  87925. return "AnaglyphFreeCamera";
  87926. };
  87927. return AnaglyphFreeCamera;
  87928. }(BABYLON.FreeCamera));
  87929. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87930. /**
  87931. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87932. */
  87933. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87934. __extends(AnaglyphArcRotateCamera, _super);
  87935. /**
  87936. * Creates a new AnaglyphArcRotateCamera
  87937. * @param name defines camera name
  87938. * @param alpha defines alpha angle (in radians)
  87939. * @param beta defines beta angle (in radians)
  87940. * @param radius defines radius
  87941. * @param target defines camera target
  87942. * @param interaxialDistance defines distance between each color axis
  87943. * @param scene defines the hosting scene
  87944. */
  87945. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87946. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87947. _this.interaxialDistance = interaxialDistance;
  87948. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87949. return _this;
  87950. }
  87951. /**
  87952. * Gets camera class name
  87953. * @returns AnaglyphArcRotateCamera
  87954. */
  87955. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87956. return "AnaglyphArcRotateCamera";
  87957. };
  87958. return AnaglyphArcRotateCamera;
  87959. }(BABYLON.ArcRotateCamera));
  87960. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87961. /**
  87962. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87963. */
  87964. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87965. __extends(AnaglyphGamepadCamera, _super);
  87966. /**
  87967. * Creates a new AnaglyphGamepadCamera
  87968. * @param name defines camera name
  87969. * @param position defines initial position
  87970. * @param interaxialDistance defines distance between each color axis
  87971. * @param scene defines the hosting scene
  87972. */
  87973. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87974. var _this = _super.call(this, name, position, scene) || this;
  87975. _this.interaxialDistance = interaxialDistance;
  87976. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87977. return _this;
  87978. }
  87979. /**
  87980. * Gets camera class name
  87981. * @returns AnaglyphGamepadCamera
  87982. */
  87983. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87984. return "AnaglyphGamepadCamera";
  87985. };
  87986. return AnaglyphGamepadCamera;
  87987. }(BABYLON.GamepadCamera));
  87988. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87989. /**
  87990. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87991. */
  87992. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87993. __extends(AnaglyphUniversalCamera, _super);
  87994. /**
  87995. * Creates a new AnaglyphUniversalCamera
  87996. * @param name defines camera name
  87997. * @param position defines initial position
  87998. * @param interaxialDistance defines distance between each color axis
  87999. * @param scene defines the hosting scene
  88000. */
  88001. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  88002. var _this = _super.call(this, name, position, scene) || this;
  88003. _this.interaxialDistance = interaxialDistance;
  88004. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88005. return _this;
  88006. }
  88007. /**
  88008. * Gets camera class name
  88009. * @returns AnaglyphUniversalCamera
  88010. */
  88011. AnaglyphUniversalCamera.prototype.getClassName = function () {
  88012. return "AnaglyphUniversalCamera";
  88013. };
  88014. return AnaglyphUniversalCamera;
  88015. }(BABYLON.UniversalCamera));
  88016. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  88017. /**
  88018. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  88019. */
  88020. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  88021. __extends(StereoscopicFreeCamera, _super);
  88022. /**
  88023. * Creates a new StereoscopicFreeCamera
  88024. * @param name defines camera name
  88025. * @param position defines initial position
  88026. * @param interaxialDistance defines distance between each color axis
  88027. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88028. * @param scene defines the hosting scene
  88029. */
  88030. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88031. var _this = _super.call(this, name, position, scene) || this;
  88032. _this.interaxialDistance = interaxialDistance;
  88033. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88034. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88035. return _this;
  88036. }
  88037. /**
  88038. * Gets camera class name
  88039. * @returns StereoscopicFreeCamera
  88040. */
  88041. StereoscopicFreeCamera.prototype.getClassName = function () {
  88042. return "StereoscopicFreeCamera";
  88043. };
  88044. return StereoscopicFreeCamera;
  88045. }(BABYLON.FreeCamera));
  88046. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  88047. /**
  88048. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  88049. */
  88050. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  88051. __extends(StereoscopicArcRotateCamera, _super);
  88052. /**
  88053. * Creates a new StereoscopicArcRotateCamera
  88054. * @param name defines camera name
  88055. * @param alpha defines alpha angle (in radians)
  88056. * @param beta defines beta angle (in radians)
  88057. * @param radius defines radius
  88058. * @param target defines camera target
  88059. * @param interaxialDistance defines distance between each color axis
  88060. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88061. * @param scene defines the hosting scene
  88062. */
  88063. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  88064. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88065. _this.interaxialDistance = interaxialDistance;
  88066. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88067. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88068. return _this;
  88069. }
  88070. /**
  88071. * Gets camera class name
  88072. * @returns StereoscopicArcRotateCamera
  88073. */
  88074. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  88075. return "StereoscopicArcRotateCamera";
  88076. };
  88077. return StereoscopicArcRotateCamera;
  88078. }(BABYLON.ArcRotateCamera));
  88079. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  88080. /**
  88081. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  88082. */
  88083. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  88084. __extends(StereoscopicGamepadCamera, _super);
  88085. /**
  88086. * Creates a new StereoscopicGamepadCamera
  88087. * @param name defines camera name
  88088. * @param position defines initial position
  88089. * @param interaxialDistance defines distance between each color axis
  88090. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88091. * @param scene defines the hosting scene
  88092. */
  88093. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88094. var _this = _super.call(this, name, position, scene) || this;
  88095. _this.interaxialDistance = interaxialDistance;
  88096. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88097. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88098. return _this;
  88099. }
  88100. /**
  88101. * Gets camera class name
  88102. * @returns StereoscopicGamepadCamera
  88103. */
  88104. StereoscopicGamepadCamera.prototype.getClassName = function () {
  88105. return "StereoscopicGamepadCamera";
  88106. };
  88107. return StereoscopicGamepadCamera;
  88108. }(BABYLON.GamepadCamera));
  88109. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  88110. /**
  88111. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  88112. */
  88113. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  88114. __extends(StereoscopicUniversalCamera, _super);
  88115. /**
  88116. * Creates a new StereoscopicUniversalCamera
  88117. * @param name defines camera name
  88118. * @param position defines initial position
  88119. * @param interaxialDistance defines distance between each color axis
  88120. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88121. * @param scene defines the hosting scene
  88122. */
  88123. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88124. var _this = _super.call(this, name, position, scene) || this;
  88125. _this.interaxialDistance = interaxialDistance;
  88126. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88127. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88128. return _this;
  88129. }
  88130. /**
  88131. * Gets camera class name
  88132. * @returns StereoscopicUniversalCamera
  88133. */
  88134. StereoscopicUniversalCamera.prototype.getClassName = function () {
  88135. return "StereoscopicUniversalCamera";
  88136. };
  88137. return StereoscopicUniversalCamera;
  88138. }(BABYLON.UniversalCamera));
  88139. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  88140. })(BABYLON || (BABYLON = {}));
  88141. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  88142. var BABYLON;
  88143. (function (BABYLON) {
  88144. var VRExperienceHelperGazer = /** @class */ (function () {
  88145. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  88146. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  88147. this.scene = scene;
  88148. this._pointerDownOnMeshAsked = false;
  88149. this._isActionableMesh = false;
  88150. this._teleportationRequestInitiated = false;
  88151. this._teleportationBackRequestInitiated = false;
  88152. this._rotationRightAsked = false;
  88153. this._rotationLeftAsked = false;
  88154. this._dpadPressed = true;
  88155. this._activePointer = false;
  88156. this._id = VRExperienceHelperGazer._idCounter++;
  88157. // Gaze tracker
  88158. if (!gazeTrackerToClone) {
  88159. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  88160. this._gazeTracker.bakeCurrentTransformIntoVertices();
  88161. this._gazeTracker.isPickable = false;
  88162. this._gazeTracker.isVisible = false;
  88163. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  88164. targetMat.specularColor = BABYLON.Color3.Black();
  88165. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88166. targetMat.backFaceCulling = false;
  88167. this._gazeTracker.material = targetMat;
  88168. }
  88169. else {
  88170. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  88171. }
  88172. }
  88173. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  88174. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  88175. };
  88176. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  88177. this._pointerDownOnMeshAsked = true;
  88178. if (this._currentHit) {
  88179. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  88180. }
  88181. };
  88182. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  88183. if (this._currentHit) {
  88184. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  88185. }
  88186. this._pointerDownOnMeshAsked = false;
  88187. };
  88188. VRExperienceHelperGazer.prototype._activatePointer = function () {
  88189. this._activePointer = true;
  88190. };
  88191. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  88192. this._activePointer = false;
  88193. };
  88194. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  88195. if (distance === void 0) { distance = 100; }
  88196. };
  88197. VRExperienceHelperGazer.prototype.dispose = function () {
  88198. this._interactionsEnabled = false;
  88199. this._teleportationEnabled = false;
  88200. if (this._gazeTracker) {
  88201. this._gazeTracker.dispose();
  88202. }
  88203. };
  88204. VRExperienceHelperGazer._idCounter = 0;
  88205. return VRExperienceHelperGazer;
  88206. }());
  88207. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  88208. __extends(VRExperienceHelperControllerGazer, _super);
  88209. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  88210. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  88211. _this.webVRController = webVRController;
  88212. // Laser pointer
  88213. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  88214. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  88215. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88216. laserPointerMaterial.alpha = 0.6;
  88217. _this._laserPointer.material = laserPointerMaterial;
  88218. _this._laserPointer.rotation.x = Math.PI / 2;
  88219. _this._laserPointer.position.z = -0.5;
  88220. _this._laserPointer.isVisible = false;
  88221. if (!webVRController.mesh) {
  88222. // Create an empty mesh that is used prior to loading the high quality model
  88223. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  88224. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  88225. preloadPointerPose.rotation.x = -0.7;
  88226. preloadMesh.addChild(preloadPointerPose);
  88227. webVRController.attachToMesh(preloadMesh);
  88228. }
  88229. _this._setLaserPointerParent(webVRController.mesh);
  88230. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  88231. _this._setLaserPointerParent(mesh);
  88232. });
  88233. return _this;
  88234. }
  88235. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  88236. return this.webVRController.getForwardRay(length);
  88237. };
  88238. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  88239. _super.prototype._activatePointer.call(this);
  88240. this._laserPointer.isVisible = true;
  88241. };
  88242. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  88243. _super.prototype._deactivatePointer.call(this);
  88244. this._laserPointer.isVisible = false;
  88245. };
  88246. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  88247. this._laserPointer.material.emissiveColor = color;
  88248. };
  88249. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  88250. var makeNotPick = function (root) {
  88251. root.name += " laserPointer";
  88252. root.getChildMeshes().forEach(function (c) {
  88253. makeNotPick(c);
  88254. });
  88255. };
  88256. makeNotPick(mesh);
  88257. var childMeshes = mesh.getChildMeshes();
  88258. this.webVRController._pointingPoseNode = null;
  88259. for (var i = 0; i < childMeshes.length; i++) {
  88260. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  88261. mesh = childMeshes[i];
  88262. this.webVRController._pointingPoseNode = mesh;
  88263. break;
  88264. }
  88265. }
  88266. this._laserPointer.parent = mesh;
  88267. };
  88268. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  88269. if (distance === void 0) { distance = 100; }
  88270. this._laserPointer.scaling.y = distance;
  88271. this._laserPointer.position.z = -distance / 2;
  88272. };
  88273. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  88274. _super.prototype.dispose.call(this);
  88275. this._laserPointer.dispose();
  88276. if (this._meshAttachedObserver) {
  88277. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  88278. }
  88279. };
  88280. return VRExperienceHelperControllerGazer;
  88281. }(VRExperienceHelperGazer));
  88282. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  88283. __extends(VRExperienceHelperCameraGazer, _super);
  88284. function VRExperienceHelperCameraGazer(getCamera, scene) {
  88285. var _this = _super.call(this, scene) || this;
  88286. _this.getCamera = getCamera;
  88287. return _this;
  88288. }
  88289. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  88290. var camera = this.getCamera();
  88291. if (camera) {
  88292. return camera.getForwardRay(length);
  88293. }
  88294. else {
  88295. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  88296. }
  88297. };
  88298. return VRExperienceHelperCameraGazer;
  88299. }(VRExperienceHelperGazer));
  88300. /**
  88301. * Helps to quickly add VR support to an existing scene.
  88302. * See http://doc.babylonjs.com/how_to/webvr_helper
  88303. */
  88304. var VRExperienceHelper = /** @class */ (function () {
  88305. /**
  88306. * Instantiates a VRExperienceHelper.
  88307. * Helps to quickly add VR support to an existing scene.
  88308. * @param scene The scene the VRExperienceHelper belongs to.
  88309. * @param webVROptions Options to modify the vr experience helper's behavior.
  88310. */
  88311. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  88312. if (webVROptions === void 0) { webVROptions = {}; }
  88313. var _this = this;
  88314. this.webVROptions = webVROptions;
  88315. // Can the system support WebVR, even if a headset isn't plugged in?
  88316. this._webVRsupported = false;
  88317. // If WebVR is supported, is a headset plugged in and are we ready to present?
  88318. this._webVRready = false;
  88319. // Are we waiting for the requestPresent callback to complete?
  88320. this._webVRrequesting = false;
  88321. // Are we presenting to the headset right now?
  88322. this._webVRpresenting = false;
  88323. // Are we presenting in the fullscreen fallback?
  88324. this._fullscreenVRpresenting = false;
  88325. /**
  88326. * Observable raised when entering VR.
  88327. */
  88328. this.onEnteringVRObservable = new BABYLON.Observable();
  88329. /**
  88330. * Observable raised when exiting VR.
  88331. */
  88332. this.onExitingVRObservable = new BABYLON.Observable();
  88333. /**
  88334. * Observable raised when controller mesh is loaded.
  88335. */
  88336. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88337. this._useCustomVRButton = false;
  88338. this._teleportationRequested = false;
  88339. this._teleportActive = false;
  88340. this._floorMeshesCollection = [];
  88341. this._rotationAllowed = true;
  88342. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  88343. this._isDefaultTeleportationTarget = true;
  88344. this._teleportationFillColor = "#444444";
  88345. this._teleportationBorderColor = "#FFFFFF";
  88346. this._rotationAngle = 0;
  88347. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  88348. this._padSensibilityUp = 0.65;
  88349. this._padSensibilityDown = 0.35;
  88350. this.leftController = null;
  88351. this.rightController = null;
  88352. /**
  88353. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  88354. */
  88355. this.onNewMeshSelected = new BABYLON.Observable();
  88356. /**
  88357. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  88358. */
  88359. this.onNewMeshPicked = new BABYLON.Observable();
  88360. /**
  88361. * Observable raised before camera teleportation
  88362. */
  88363. this.onBeforeCameraTeleport = new BABYLON.Observable();
  88364. /**
  88365. * Observable raised after camera teleportation
  88366. */
  88367. this.onAfterCameraTeleport = new BABYLON.Observable();
  88368. /**
  88369. * Observable raised when current selected mesh gets unselected
  88370. */
  88371. this.onSelectedMeshUnselected = new BABYLON.Observable();
  88372. /**
  88373. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  88374. */
  88375. this.teleportationEnabled = true;
  88376. this._teleportationInitialized = false;
  88377. this._interactionsEnabled = false;
  88378. this._interactionsRequested = false;
  88379. this._displayGaze = true;
  88380. this._displayLaserPointer = true;
  88381. this._onResize = function () {
  88382. _this.moveButtonToBottomRight();
  88383. if (_this._fullscreenVRpresenting && _this._webVRready) {
  88384. _this.exitVR();
  88385. }
  88386. };
  88387. this._onFullscreenChange = function () {
  88388. if (document.fullscreen !== undefined) {
  88389. _this._fullscreenVRpresenting = document.fullscreen;
  88390. }
  88391. else if (document.mozFullScreen !== undefined) {
  88392. _this._fullscreenVRpresenting = document.mozFullScreen;
  88393. }
  88394. else if (document.webkitIsFullScreen !== undefined) {
  88395. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  88396. }
  88397. else if (document.msIsFullScreen !== undefined) {
  88398. _this._fullscreenVRpresenting = document.msIsFullScreen;
  88399. }
  88400. if (!_this._fullscreenVRpresenting && _this._canvas) {
  88401. _this.exitVR();
  88402. if (!_this._useCustomVRButton) {
  88403. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  88404. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  88405. }
  88406. }
  88407. };
  88408. this.beforeRender = function () {
  88409. if (_this.leftController && _this.leftController._activePointer) {
  88410. _this._castRayAndSelectObject(_this.leftController);
  88411. }
  88412. if (_this.rightController && _this.rightController._activePointer) {
  88413. _this._castRayAndSelectObject(_this.rightController);
  88414. }
  88415. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  88416. _this._castRayAndSelectObject(_this._cameraGazer);
  88417. }
  88418. else {
  88419. _this._cameraGazer._gazeTracker.isVisible = false;
  88420. }
  88421. };
  88422. this._onNewGamepadConnected = function (gamepad) {
  88423. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  88424. if (gamepad.leftStick) {
  88425. gamepad.onleftstickchanged(function (stickValues) {
  88426. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  88427. // Listening to classic/xbox gamepad only if no VR controller is active
  88428. if ((!_this.leftController && !_this.rightController) ||
  88429. ((_this.leftController && !_this.leftController._activePointer) &&
  88430. (_this.rightController && !_this.rightController._activePointer))) {
  88431. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  88432. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  88433. }
  88434. }
  88435. });
  88436. }
  88437. if (gamepad.rightStick) {
  88438. gamepad.onrightstickchanged(function (stickValues) {
  88439. if (_this._teleportationInitialized) {
  88440. _this._checkRotate(stickValues, _this._cameraGazer);
  88441. }
  88442. });
  88443. }
  88444. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  88445. gamepad.onbuttondown(function (buttonPressed) {
  88446. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88447. _this._cameraGazer._selectionPointerDown();
  88448. }
  88449. });
  88450. gamepad.onbuttonup(function (buttonPressed) {
  88451. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88452. _this._cameraGazer._selectionPointerUp();
  88453. }
  88454. });
  88455. }
  88456. }
  88457. else {
  88458. var webVRController = gamepad;
  88459. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  88460. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  88461. _this.rightController = controller;
  88462. }
  88463. else {
  88464. _this.leftController = controller;
  88465. }
  88466. _this._tryEnableInteractionOnController(controller);
  88467. }
  88468. };
  88469. // 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
  88470. this._tryEnableInteractionOnController = function (controller) {
  88471. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  88472. _this._enableInteractionOnController(controller);
  88473. }
  88474. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  88475. _this._enableTeleportationOnController(controller);
  88476. }
  88477. };
  88478. this._onNewGamepadDisconnected = function (gamepad) {
  88479. if (gamepad instanceof BABYLON.WebVRController) {
  88480. if (gamepad.hand === "left" && _this.leftController != null) {
  88481. _this.leftController.dispose();
  88482. _this.leftController = null;
  88483. }
  88484. if (gamepad.hand === "right" && _this.rightController != null) {
  88485. _this.rightController.dispose();
  88486. _this.rightController = null;
  88487. }
  88488. }
  88489. };
  88490. this._workingVector = BABYLON.Vector3.Zero();
  88491. this._workingQuaternion = BABYLON.Quaternion.Identity();
  88492. this._workingMatrix = BABYLON.Matrix.Identity();
  88493. this._scene = scene;
  88494. this._canvas = scene.getEngine().getRenderingCanvas();
  88495. // Parse options
  88496. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  88497. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  88498. }
  88499. if (webVROptions.createDeviceOrientationCamera === undefined) {
  88500. webVROptions.createDeviceOrientationCamera = true;
  88501. }
  88502. if (webVROptions.laserToggle === undefined) {
  88503. webVROptions.laserToggle = true;
  88504. }
  88505. if (webVROptions.defaultHeight === undefined) {
  88506. webVROptions.defaultHeight = 1.7;
  88507. }
  88508. if (webVROptions.useCustomVRButton) {
  88509. this._useCustomVRButton = true;
  88510. if (webVROptions.customVRButton) {
  88511. this._btnVR = webVROptions.customVRButton;
  88512. }
  88513. }
  88514. if (webVROptions.rayLength) {
  88515. this._rayLength = webVROptions.rayLength;
  88516. }
  88517. this._defaultHeight = webVROptions.defaultHeight;
  88518. if (webVROptions.positionScale) {
  88519. this._rayLength *= webVROptions.positionScale;
  88520. this._defaultHeight *= webVROptions.positionScale;
  88521. }
  88522. // Set position
  88523. if (this._scene.activeCamera) {
  88524. this._position = this._scene.activeCamera.position.clone();
  88525. }
  88526. else {
  88527. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88528. }
  88529. // Set non-vr camera
  88530. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88531. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88532. // Copy data from existing camera
  88533. if (this._scene.activeCamera) {
  88534. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88535. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88536. // Set rotation from previous camera
  88537. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88538. var targetCamera = this._scene.activeCamera;
  88539. if (targetCamera.rotationQuaternion) {
  88540. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88541. }
  88542. else {
  88543. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88544. }
  88545. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88546. }
  88547. }
  88548. this._scene.activeCamera = this._deviceOrientationCamera;
  88549. if (this._canvas) {
  88550. this._scene.activeCamera.attachControl(this._canvas);
  88551. }
  88552. }
  88553. else {
  88554. this._existingCamera = this._scene.activeCamera;
  88555. }
  88556. // Create VR cameras
  88557. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88558. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88559. }
  88560. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88561. this._webVRCamera.useStandingMatrix();
  88562. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88563. // Create default button
  88564. if (!this._useCustomVRButton) {
  88565. this._btnVR = document.createElement("BUTTON");
  88566. this._btnVR.className = "babylonVRicon";
  88567. this._btnVR.id = "babylonVRiconbtn";
  88568. this._btnVR.title = "Click to switch to VR";
  88569. 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) }";
  88570. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88571. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88572. // css += ".babylonVRicon.vrdisplaysupported { }";
  88573. // css += ".babylonVRicon.vrdisplayready { }";
  88574. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88575. var style = document.createElement('style');
  88576. style.appendChild(document.createTextNode(css));
  88577. document.getElementsByTagName('head')[0].appendChild(style);
  88578. this.moveButtonToBottomRight();
  88579. }
  88580. // VR button click event
  88581. if (this._btnVR) {
  88582. this._btnVR.addEventListener("click", function () {
  88583. if (!_this.isInVRMode) {
  88584. _this.enterVR();
  88585. }
  88586. else {
  88587. _this.exitVR();
  88588. }
  88589. });
  88590. }
  88591. // Window events
  88592. window.addEventListener("resize", this._onResize);
  88593. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88594. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88595. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88596. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88597. // Display vr button when headset is connected
  88598. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88599. this.displayVRButton();
  88600. }
  88601. else {
  88602. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88603. if (e.vrDisplay) {
  88604. _this.displayVRButton();
  88605. }
  88606. });
  88607. }
  88608. // Exiting VR mode using 'ESC' key on desktop
  88609. this._onKeyDown = function (event) {
  88610. if (event.keyCode === 27 && _this.isInVRMode) {
  88611. _this.exitVR();
  88612. }
  88613. };
  88614. document.addEventListener("keydown", this._onKeyDown);
  88615. // Exiting VR mode double tapping the touch screen
  88616. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88617. if (_this.isInVRMode) {
  88618. _this.exitVR();
  88619. if (_this._fullscreenVRpresenting) {
  88620. _this._scene.getEngine().switchFullscreen(true);
  88621. }
  88622. }
  88623. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88624. // Listen for WebVR display changes
  88625. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88626. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88627. this._onVRRequestPresentStart = function () {
  88628. _this._webVRrequesting = true;
  88629. _this.updateButtonVisibility();
  88630. };
  88631. this._onVRRequestPresentComplete = function (success) {
  88632. _this._webVRrequesting = false;
  88633. _this.updateButtonVisibility();
  88634. };
  88635. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88636. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88637. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88638. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88639. scene.onDisposeObservable.add(function () {
  88640. _this.dispose();
  88641. });
  88642. // Gamepad connection events
  88643. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88644. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88645. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88646. this.updateButtonVisibility();
  88647. //create easing functions
  88648. this._circleEase = new BABYLON.CircleEase();
  88649. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88650. if (this.webVROptions.floorMeshes) {
  88651. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  88652. }
  88653. }
  88654. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88655. /** Return this.onEnteringVRObservable
  88656. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88657. */
  88658. get: function () {
  88659. return this.onEnteringVRObservable;
  88660. },
  88661. enumerable: true,
  88662. configurable: true
  88663. });
  88664. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88665. /** Return this.onExitingVRObservable
  88666. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88667. */
  88668. get: function () {
  88669. return this.onExitingVRObservable;
  88670. },
  88671. enumerable: true,
  88672. configurable: true
  88673. });
  88674. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88675. /** Return this.onControllerMeshLoadedObservable
  88676. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88677. */
  88678. get: function () {
  88679. return this.onControllerMeshLoadedObservable;
  88680. },
  88681. enumerable: true,
  88682. configurable: true
  88683. });
  88684. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88685. /**
  88686. * The mesh used to display where the user is going to teleport.
  88687. */
  88688. get: function () {
  88689. return this._teleportationTarget;
  88690. },
  88691. /**
  88692. * Sets the mesh to be used to display where the user is going to teleport.
  88693. */
  88694. set: function (value) {
  88695. if (value) {
  88696. value.name = "teleportationTarget";
  88697. this._isDefaultTeleportationTarget = false;
  88698. this._teleportationTarget = value;
  88699. }
  88700. },
  88701. enumerable: true,
  88702. configurable: true
  88703. });
  88704. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88705. /**
  88706. * The mesh used to display where the user is selecting,
  88707. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88708. * See http://doc.babylonjs.com/resources/baking_transformations
  88709. */
  88710. get: function () {
  88711. return this._cameraGazer._gazeTracker;
  88712. },
  88713. set: function (value) {
  88714. if (value) {
  88715. this._cameraGazer._gazeTracker = value;
  88716. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88717. this._cameraGazer._gazeTracker.isPickable = false;
  88718. this._cameraGazer._gazeTracker.isVisible = false;
  88719. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88720. if (this.leftController) {
  88721. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88722. }
  88723. if (this.rightController) {
  88724. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88725. }
  88726. }
  88727. },
  88728. enumerable: true,
  88729. configurable: true
  88730. });
  88731. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88732. /**
  88733. * If the ray of the gaze should be displayed.
  88734. */
  88735. get: function () {
  88736. return this._displayGaze;
  88737. },
  88738. /**
  88739. * Sets if the ray of the gaze should be displayed.
  88740. */
  88741. set: function (value) {
  88742. this._displayGaze = value;
  88743. if (!value) {
  88744. this._cameraGazer._gazeTracker.isVisible = false;
  88745. if (this.leftController) {
  88746. this.leftController._gazeTracker.isVisible = false;
  88747. }
  88748. if (this.rightController) {
  88749. this.rightController._gazeTracker.isVisible = false;
  88750. }
  88751. }
  88752. },
  88753. enumerable: true,
  88754. configurable: true
  88755. });
  88756. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88757. /**
  88758. * If the ray of the LaserPointer should be displayed.
  88759. */
  88760. get: function () {
  88761. return this._displayLaserPointer;
  88762. },
  88763. /**
  88764. * Sets if the ray of the LaserPointer should be displayed.
  88765. */
  88766. set: function (value) {
  88767. this._displayLaserPointer = value;
  88768. if (!value) {
  88769. if (this.rightController) {
  88770. this.rightController._deactivatePointer();
  88771. this.rightController._gazeTracker.isVisible = false;
  88772. }
  88773. if (this.leftController) {
  88774. this.leftController._deactivatePointer();
  88775. this.leftController._gazeTracker.isVisible = false;
  88776. }
  88777. }
  88778. else {
  88779. if (this.rightController) {
  88780. this.rightController._activatePointer();
  88781. }
  88782. if (this.leftController) {
  88783. this.leftController._activatePointer();
  88784. }
  88785. }
  88786. },
  88787. enumerable: true,
  88788. configurable: true
  88789. });
  88790. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88791. /**
  88792. * The deviceOrientationCamera used as the camera when not in VR.
  88793. */
  88794. get: function () {
  88795. return this._deviceOrientationCamera;
  88796. },
  88797. enumerable: true,
  88798. configurable: true
  88799. });
  88800. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88801. /**
  88802. * Based on the current WebVR support, returns the current VR camera used.
  88803. */
  88804. get: function () {
  88805. if (this._webVRready) {
  88806. return this._webVRCamera;
  88807. }
  88808. else {
  88809. return this._scene.activeCamera;
  88810. }
  88811. },
  88812. enumerable: true,
  88813. configurable: true
  88814. });
  88815. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88816. /**
  88817. * The webVRCamera which is used when in VR.
  88818. */
  88819. get: function () {
  88820. return this._webVRCamera;
  88821. },
  88822. enumerable: true,
  88823. configurable: true
  88824. });
  88825. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88826. /**
  88827. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88828. */
  88829. get: function () {
  88830. return this._vrDeviceOrientationCamera;
  88831. },
  88832. enumerable: true,
  88833. configurable: true
  88834. });
  88835. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88836. get: function () {
  88837. var result = this._cameraGazer._teleportationRequestInitiated
  88838. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88839. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88840. return result;
  88841. },
  88842. enumerable: true,
  88843. configurable: true
  88844. });
  88845. // Raised when one of the controller has loaded successfully its associated default mesh
  88846. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88847. if (this.leftController && this.leftController.webVRController == webVRController) {
  88848. if (webVRController.mesh) {
  88849. this.leftController._setLaserPointerParent(webVRController.mesh);
  88850. }
  88851. }
  88852. if (this.rightController && this.rightController.webVRController == webVRController) {
  88853. if (webVRController.mesh) {
  88854. this.rightController._setLaserPointerParent(webVRController.mesh);
  88855. }
  88856. }
  88857. try {
  88858. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88859. }
  88860. catch (err) {
  88861. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88862. }
  88863. };
  88864. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88865. /**
  88866. * Gets a value indicating if we are currently in VR mode.
  88867. */
  88868. get: function () {
  88869. return this._webVRpresenting || this._fullscreenVRpresenting;
  88870. },
  88871. enumerable: true,
  88872. configurable: true
  88873. });
  88874. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88875. var vrDisplay = this._scene.getEngine().getVRDevice();
  88876. if (vrDisplay) {
  88877. var wasPresenting = this._webVRpresenting;
  88878. // A VR display is connected
  88879. this._webVRpresenting = vrDisplay.isPresenting;
  88880. if (wasPresenting && !this._webVRpresenting)
  88881. this.exitVR();
  88882. }
  88883. else {
  88884. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88885. }
  88886. this.updateButtonVisibility();
  88887. };
  88888. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88889. this._webVRsupported = eventArgs.vrSupported;
  88890. this._webVRready = !!eventArgs.vrDisplay;
  88891. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88892. this.updateButtonVisibility();
  88893. };
  88894. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88895. if (this._canvas && !this._useCustomVRButton) {
  88896. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88897. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88898. }
  88899. };
  88900. VRExperienceHelper.prototype.displayVRButton = function () {
  88901. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88902. document.body.appendChild(this._btnVR);
  88903. this._btnVRDisplayed = true;
  88904. }
  88905. };
  88906. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88907. if (!this._btnVR || this._useCustomVRButton) {
  88908. return;
  88909. }
  88910. this._btnVR.className = "babylonVRicon";
  88911. if (this.isInVRMode) {
  88912. this._btnVR.className += " vrdisplaypresenting";
  88913. }
  88914. else {
  88915. if (this._webVRready)
  88916. this._btnVR.className += " vrdisplayready";
  88917. if (this._webVRsupported)
  88918. this._btnVR.className += " vrdisplaysupported";
  88919. if (this._webVRrequesting)
  88920. this._btnVR.className += " vrdisplayrequesting";
  88921. }
  88922. };
  88923. /**
  88924. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88925. * Otherwise, will use the fullscreen API.
  88926. */
  88927. VRExperienceHelper.prototype.enterVR = function () {
  88928. if (this.onEnteringVRObservable) {
  88929. try {
  88930. this.onEnteringVRObservable.notifyObservers(this);
  88931. }
  88932. catch (err) {
  88933. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88934. }
  88935. }
  88936. if (this._scene.activeCamera) {
  88937. this._position = this._scene.activeCamera.position.clone();
  88938. // make sure that we return to the last active camera
  88939. this._existingCamera = this._scene.activeCamera;
  88940. }
  88941. if (this._webVRrequesting)
  88942. return;
  88943. // If WebVR is supported and a headset is connected
  88944. if (this._webVRready) {
  88945. if (!this._webVRpresenting) {
  88946. this._webVRCamera.position = this._position;
  88947. this._scene.activeCamera = this._webVRCamera;
  88948. }
  88949. }
  88950. else if (this._vrDeviceOrientationCamera) {
  88951. this._vrDeviceOrientationCamera.position = this._position;
  88952. if (this._scene.activeCamera) {
  88953. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88954. }
  88955. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88956. this._scene.getEngine().switchFullscreen(true);
  88957. this.updateButtonVisibility();
  88958. }
  88959. if (this._scene.activeCamera && this._canvas) {
  88960. this._scene.activeCamera.attachControl(this._canvas);
  88961. }
  88962. if (this._interactionsEnabled) {
  88963. this._scene.registerBeforeRender(this.beforeRender);
  88964. }
  88965. };
  88966. /**
  88967. * Attempt to exit VR, or fullscreen.
  88968. */
  88969. VRExperienceHelper.prototype.exitVR = function () {
  88970. if (this.onExitingVRObservable) {
  88971. try {
  88972. this.onExitingVRObservable.notifyObservers(this);
  88973. }
  88974. catch (err) {
  88975. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88976. }
  88977. }
  88978. if (this._webVRpresenting) {
  88979. this._scene.getEngine().disableVR();
  88980. }
  88981. if (this._scene.activeCamera) {
  88982. this._position = this._scene.activeCamera.position.clone();
  88983. }
  88984. if (this._deviceOrientationCamera) {
  88985. this._deviceOrientationCamera.position = this._position;
  88986. this._scene.activeCamera = this._deviceOrientationCamera;
  88987. if (this._canvas) {
  88988. this._scene.activeCamera.attachControl(this._canvas);
  88989. }
  88990. }
  88991. else if (this._existingCamera) {
  88992. this._existingCamera.position = this._position;
  88993. this._scene.activeCamera = this._existingCamera;
  88994. }
  88995. this.updateButtonVisibility();
  88996. if (this._interactionsEnabled) {
  88997. this._scene.unregisterBeforeRender(this.beforeRender);
  88998. }
  88999. // resize to update width and height when exiting vr exits fullscreen
  89000. this._scene.getEngine().resize();
  89001. };
  89002. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  89003. /**
  89004. * The position of the vr experience helper.
  89005. */
  89006. get: function () {
  89007. return this._position;
  89008. },
  89009. /**
  89010. * Sets the position of the vr experience helper.
  89011. */
  89012. set: function (value) {
  89013. this._position = value;
  89014. if (this._scene.activeCamera) {
  89015. this._scene.activeCamera.position = value;
  89016. }
  89017. },
  89018. enumerable: true,
  89019. configurable: true
  89020. });
  89021. /**
  89022. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  89023. */
  89024. VRExperienceHelper.prototype.enableInteractions = function () {
  89025. var _this = this;
  89026. if (!this._interactionsEnabled) {
  89027. this._interactionsRequested = true;
  89028. if (this.leftController) {
  89029. this._enableInteractionOnController(this.leftController);
  89030. }
  89031. if (this.rightController) {
  89032. this._enableInteractionOnController(this.rightController);
  89033. }
  89034. this.raySelectionPredicate = function (mesh) {
  89035. return mesh.isVisible;
  89036. };
  89037. this.meshSelectionPredicate = function (mesh) {
  89038. return true;
  89039. };
  89040. this._raySelectionPredicate = function (mesh) {
  89041. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  89042. && mesh.name.indexOf("teleportationTarget") === -1
  89043. && mesh.name.indexOf("torusTeleportation") === -1
  89044. && mesh.name.indexOf("laserPointer") === -1)) {
  89045. return _this.raySelectionPredicate(mesh);
  89046. }
  89047. return false;
  89048. };
  89049. this._interactionsEnabled = true;
  89050. }
  89051. };
  89052. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  89053. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  89054. if (this._floorMeshesCollection[i].id === mesh.id) {
  89055. return true;
  89056. }
  89057. }
  89058. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  89059. return true;
  89060. }
  89061. return false;
  89062. };
  89063. /**
  89064. * Adds a floor mesh to be used for teleportation.
  89065. * @param floorMesh the mesh to be used for teleportation.
  89066. */
  89067. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  89068. if (!this._floorMeshesCollection) {
  89069. return;
  89070. }
  89071. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  89072. return;
  89073. }
  89074. this._floorMeshesCollection.push(floorMesh);
  89075. };
  89076. /**
  89077. * Removes a floor mesh from being used for teleportation.
  89078. * @param floorMesh the mesh to be removed.
  89079. */
  89080. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  89081. if (!this._floorMeshesCollection) {
  89082. return;
  89083. }
  89084. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  89085. if (meshIndex !== -1) {
  89086. this._floorMeshesCollection.splice(meshIndex, 1);
  89087. }
  89088. };
  89089. /**
  89090. * Enables interactions and teleportation using the VR controllers and gaze.
  89091. * @param vrTeleportationOptions options to modify teleportation behavior.
  89092. */
  89093. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  89094. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  89095. if (!this._teleportationInitialized) {
  89096. this._teleportationRequested = true;
  89097. this.enableInteractions();
  89098. if (vrTeleportationOptions.floorMeshName) {
  89099. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  89100. }
  89101. if (vrTeleportationOptions.floorMeshes) {
  89102. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  89103. }
  89104. if (this.leftController != null) {
  89105. this._enableTeleportationOnController(this.leftController);
  89106. }
  89107. if (this.rightController != null) {
  89108. this._enableTeleportationOnController(this.rightController);
  89109. }
  89110. // Creates an image processing post process for the vignette not relying
  89111. // on the main scene configuration for image processing to reduce setup and spaces
  89112. // (gamma/linear) conflicts.
  89113. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  89114. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  89115. imageProcessingConfiguration.vignetteEnabled = true;
  89116. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  89117. this._webVRCamera.detachPostProcess(this._postProcessMove);
  89118. this._teleportationInitialized = true;
  89119. if (this._isDefaultTeleportationTarget) {
  89120. this._createTeleportationCircles();
  89121. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  89122. }
  89123. }
  89124. };
  89125. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  89126. var _this = this;
  89127. var controllerMesh = controller.webVRController.mesh;
  89128. if (controllerMesh) {
  89129. controller._interactionsEnabled = true;
  89130. controller._activatePointer();
  89131. if (this.webVROptions.laserToggle) {
  89132. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  89133. // Enabling / disabling laserPointer
  89134. if (_this._displayLaserPointer && stateObject.value === 1) {
  89135. if (controller._activePointer) {
  89136. controller._deactivatePointer();
  89137. }
  89138. else {
  89139. controller._activatePointer();
  89140. }
  89141. if (_this.displayGaze) {
  89142. controller._gazeTracker.isVisible = controller._activePointer;
  89143. }
  89144. }
  89145. });
  89146. }
  89147. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  89148. if (!controller._pointerDownOnMeshAsked) {
  89149. if (stateObject.value > _this._padSensibilityUp) {
  89150. controller._selectionPointerDown();
  89151. }
  89152. }
  89153. else if (stateObject.value < _this._padSensibilityDown) {
  89154. controller._selectionPointerUp();
  89155. }
  89156. });
  89157. }
  89158. };
  89159. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  89160. // Dont teleport if another gaze already requested teleportation
  89161. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  89162. return;
  89163. }
  89164. if (!gazer._teleportationRequestInitiated) {
  89165. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  89166. gazer._activatePointer();
  89167. gazer._teleportationRequestInitiated = true;
  89168. }
  89169. }
  89170. else {
  89171. // Listening to the proper controller values changes to confirm teleportation
  89172. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  89173. if (this._teleportActive) {
  89174. this._teleportCamera(this._haloCenter);
  89175. }
  89176. gazer._teleportationRequestInitiated = false;
  89177. }
  89178. }
  89179. };
  89180. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  89181. // Only rotate when user is not currently selecting a teleportation location
  89182. if (gazer._teleportationRequestInitiated) {
  89183. return;
  89184. }
  89185. if (!gazer._rotationLeftAsked) {
  89186. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  89187. gazer._rotationLeftAsked = true;
  89188. if (this._rotationAllowed) {
  89189. this._rotateCamera(false);
  89190. }
  89191. }
  89192. }
  89193. else {
  89194. if (stateObject.x > -this._padSensibilityDown) {
  89195. gazer._rotationLeftAsked = false;
  89196. }
  89197. }
  89198. if (!gazer._rotationRightAsked) {
  89199. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  89200. gazer._rotationRightAsked = true;
  89201. if (this._rotationAllowed) {
  89202. this._rotateCamera(true);
  89203. }
  89204. }
  89205. }
  89206. else {
  89207. if (stateObject.x < this._padSensibilityDown) {
  89208. gazer._rotationRightAsked = false;
  89209. }
  89210. }
  89211. };
  89212. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  89213. // Only teleport backwards when user is not currently selecting a teleportation location
  89214. if (gazer._teleportationRequestInitiated) {
  89215. return;
  89216. }
  89217. // Teleport backwards
  89218. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  89219. if (!gazer._teleportationBackRequestInitiated) {
  89220. if (!this.currentVRCamera) {
  89221. return;
  89222. }
  89223. // Get rotation and position of the current camera
  89224. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  89225. var position = this.currentVRCamera.position;
  89226. // If the camera has device position, use that instead
  89227. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  89228. rotation = this.currentVRCamera.deviceRotationQuaternion;
  89229. position = this.currentVRCamera.devicePosition;
  89230. }
  89231. // Get matrix with only the y rotation of the device rotation
  89232. rotation.toEulerAnglesToRef(this._workingVector);
  89233. this._workingVector.z = 0;
  89234. this._workingVector.x = 0;
  89235. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  89236. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  89237. // Rotate backwards ray by device rotation to cast at the ground behind the user
  89238. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  89239. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  89240. var ray = new BABYLON.Ray(position, this._workingVector);
  89241. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89242. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  89243. this._teleportCamera(hit.pickedPoint);
  89244. }
  89245. gazer._teleportationBackRequestInitiated = true;
  89246. }
  89247. }
  89248. else {
  89249. gazer._teleportationBackRequestInitiated = false;
  89250. }
  89251. };
  89252. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  89253. var _this = this;
  89254. var controllerMesh = controller.webVRController.mesh;
  89255. if (controllerMesh) {
  89256. if (!controller._interactionsEnabled) {
  89257. this._enableInteractionOnController(controller);
  89258. }
  89259. controller._interactionsEnabled = true;
  89260. controller._teleportationEnabled = true;
  89261. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  89262. controller._dpadPressed = false;
  89263. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  89264. controller._dpadPressed = stateObject.pressed;
  89265. if (!controller._dpadPressed) {
  89266. controller._rotationLeftAsked = false;
  89267. controller._rotationRightAsked = false;
  89268. controller._teleportationBackRequestInitiated = false;
  89269. }
  89270. });
  89271. }
  89272. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  89273. if (_this.teleportationEnabled) {
  89274. _this._checkTeleportBackwards(stateObject, controller);
  89275. _this._checkTeleportWithRay(stateObject, controller);
  89276. }
  89277. _this._checkRotate(stateObject, controller);
  89278. });
  89279. }
  89280. };
  89281. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  89282. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  89283. this._teleportationTarget.isPickable = false;
  89284. var length = 512;
  89285. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  89286. dynamicTexture.hasAlpha = true;
  89287. var context = dynamicTexture.getContext();
  89288. var centerX = length / 2;
  89289. var centerY = length / 2;
  89290. var radius = 200;
  89291. context.beginPath();
  89292. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  89293. context.fillStyle = this._teleportationFillColor;
  89294. context.fill();
  89295. context.lineWidth = 10;
  89296. context.strokeStyle = this._teleportationBorderColor;
  89297. context.stroke();
  89298. context.closePath();
  89299. dynamicTexture.update();
  89300. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  89301. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  89302. this._teleportationTarget.material = teleportationCircleMaterial;
  89303. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  89304. torus.isPickable = false;
  89305. torus.parent = this._teleportationTarget;
  89306. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89307. var keys = [];
  89308. keys.push({
  89309. frame: 0,
  89310. value: 0
  89311. });
  89312. keys.push({
  89313. frame: 30,
  89314. value: 0.4
  89315. });
  89316. keys.push({
  89317. frame: 60,
  89318. value: 0
  89319. });
  89320. animationInnerCircle.setKeys(keys);
  89321. var easingFunction = new BABYLON.SineEase();
  89322. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  89323. animationInnerCircle.setEasingFunction(easingFunction);
  89324. torus.animations = [];
  89325. torus.animations.push(animationInnerCircle);
  89326. this._scene.beginAnimation(torus, 0, 60, true);
  89327. this._hideTeleportationTarget();
  89328. };
  89329. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  89330. this._teleportActive = true;
  89331. if (this._teleportationInitialized) {
  89332. this._teleportationTarget.isVisible = true;
  89333. if (this._isDefaultTeleportationTarget) {
  89334. this._teleportationTarget.getChildren()[0].isVisible = true;
  89335. }
  89336. }
  89337. };
  89338. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  89339. this._teleportActive = false;
  89340. if (this._teleportationInitialized) {
  89341. this._teleportationTarget.isVisible = false;
  89342. if (this._isDefaultTeleportationTarget) {
  89343. this._teleportationTarget.getChildren()[0].isVisible = false;
  89344. }
  89345. }
  89346. };
  89347. VRExperienceHelper.prototype._rotateCamera = function (right) {
  89348. var _this = this;
  89349. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89350. return;
  89351. }
  89352. if (right) {
  89353. this._rotationAngle++;
  89354. }
  89355. else {
  89356. this._rotationAngle--;
  89357. }
  89358. this.currentVRCamera.animations = [];
  89359. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  89360. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89361. var animationRotationKeys = [];
  89362. animationRotationKeys.push({
  89363. frame: 0,
  89364. value: this.currentVRCamera.rotationQuaternion
  89365. });
  89366. animationRotationKeys.push({
  89367. frame: 6,
  89368. value: target
  89369. });
  89370. animationRotation.setKeys(animationRotationKeys);
  89371. animationRotation.setEasingFunction(this._circleEase);
  89372. this.currentVRCamera.animations.push(animationRotation);
  89373. this._postProcessMove.animations = [];
  89374. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89375. var vignetteWeightKeys = [];
  89376. vignetteWeightKeys.push({
  89377. frame: 0,
  89378. value: 0
  89379. });
  89380. vignetteWeightKeys.push({
  89381. frame: 3,
  89382. value: 4
  89383. });
  89384. vignetteWeightKeys.push({
  89385. frame: 6,
  89386. value: 0
  89387. });
  89388. animationPP.setKeys(vignetteWeightKeys);
  89389. animationPP.setEasingFunction(this._circleEase);
  89390. this._postProcessMove.animations.push(animationPP);
  89391. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89392. var vignetteStretchKeys = [];
  89393. vignetteStretchKeys.push({
  89394. frame: 0,
  89395. value: 0
  89396. });
  89397. vignetteStretchKeys.push({
  89398. frame: 3,
  89399. value: 10
  89400. });
  89401. vignetteStretchKeys.push({
  89402. frame: 6,
  89403. value: 0
  89404. });
  89405. animationPP2.setKeys(vignetteStretchKeys);
  89406. animationPP2.setEasingFunction(this._circleEase);
  89407. this._postProcessMove.animations.push(animationPP2);
  89408. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89409. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89410. this._postProcessMove.samples = 4;
  89411. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89412. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  89413. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89414. });
  89415. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  89416. };
  89417. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  89418. if (hit.pickedPoint) {
  89419. if (gazer._teleportationRequestInitiated) {
  89420. this._displayTeleportationTarget();
  89421. this._haloCenter.copyFrom(hit.pickedPoint);
  89422. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  89423. }
  89424. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  89425. if (pickNormal) {
  89426. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89427. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89428. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  89429. }
  89430. this._teleportationTarget.position.y += 0.1;
  89431. }
  89432. };
  89433. VRExperienceHelper.prototype._teleportCamera = function (location) {
  89434. var _this = this;
  89435. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89436. return;
  89437. }
  89438. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  89439. // offset of the headset from the anchor.
  89440. if (this.webVRCamera.leftCamera) {
  89441. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  89442. this._workingVector.subtractInPlace(this.webVRCamera.position);
  89443. location.subtractToRef(this._workingVector, this._workingVector);
  89444. }
  89445. else {
  89446. this._workingVector.copyFrom(location);
  89447. }
  89448. // Add height to account for user's height offset
  89449. if (this.isInVRMode) {
  89450. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  89451. }
  89452. else {
  89453. this._workingVector.y += this._defaultHeight;
  89454. }
  89455. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  89456. // Create animation from the camera's position to the new location
  89457. this.currentVRCamera.animations = [];
  89458. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89459. var animationCameraTeleportationKeys = [{
  89460. frame: 0,
  89461. value: this.currentVRCamera.position
  89462. },
  89463. {
  89464. frame: 11,
  89465. value: this._workingVector
  89466. }
  89467. ];
  89468. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  89469. animationCameraTeleportation.setEasingFunction(this._circleEase);
  89470. this.currentVRCamera.animations.push(animationCameraTeleportation);
  89471. this._postProcessMove.animations = [];
  89472. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89473. var vignetteWeightKeys = [];
  89474. vignetteWeightKeys.push({
  89475. frame: 0,
  89476. value: 0
  89477. });
  89478. vignetteWeightKeys.push({
  89479. frame: 5,
  89480. value: 8
  89481. });
  89482. vignetteWeightKeys.push({
  89483. frame: 11,
  89484. value: 0
  89485. });
  89486. animationPP.setKeys(vignetteWeightKeys);
  89487. this._postProcessMove.animations.push(animationPP);
  89488. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89489. var vignetteStretchKeys = [];
  89490. vignetteStretchKeys.push({
  89491. frame: 0,
  89492. value: 0
  89493. });
  89494. vignetteStretchKeys.push({
  89495. frame: 5,
  89496. value: 10
  89497. });
  89498. vignetteStretchKeys.push({
  89499. frame: 11,
  89500. value: 0
  89501. });
  89502. animationPP2.setKeys(vignetteStretchKeys);
  89503. this._postProcessMove.animations.push(animationPP2);
  89504. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89505. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89506. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89507. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  89508. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89509. });
  89510. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  89511. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  89512. });
  89513. this._hideTeleportationTarget();
  89514. };
  89515. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  89516. if (normal) {
  89517. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  89518. if (angle < Math.PI / 2) {
  89519. normal.scaleInPlace(-1);
  89520. }
  89521. }
  89522. return normal;
  89523. };
  89524. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  89525. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89526. return;
  89527. }
  89528. var ray = gazer._getForwardRay(this._rayLength);
  89529. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89530. if (hit) {
  89531. // Populate the contrllers mesh that can be used for drag/drop
  89532. if (gazer._laserPointer) {
  89533. hit.originMesh = gazer._laserPointer.parent;
  89534. }
  89535. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  89536. }
  89537. gazer._currentHit = hit;
  89538. // Moving the gazeTracker on the mesh face targetted
  89539. if (hit && hit.pickedPoint) {
  89540. if (this._displayGaze) {
  89541. var multiplier = 1;
  89542. gazer._gazeTracker.isVisible = true;
  89543. if (gazer._isActionableMesh) {
  89544. multiplier = 3;
  89545. }
  89546. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89547. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89548. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89549. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89550. // To avoid z-fighting
  89551. var deltaFighting = 0.002;
  89552. if (pickNormal) {
  89553. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89554. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89555. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89556. }
  89557. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89558. if (gazer._gazeTracker.position.x < 0) {
  89559. gazer._gazeTracker.position.x += deltaFighting;
  89560. }
  89561. else {
  89562. gazer._gazeTracker.position.x -= deltaFighting;
  89563. }
  89564. if (gazer._gazeTracker.position.y < 0) {
  89565. gazer._gazeTracker.position.y += deltaFighting;
  89566. }
  89567. else {
  89568. gazer._gazeTracker.position.y -= deltaFighting;
  89569. }
  89570. if (gazer._gazeTracker.position.z < 0) {
  89571. gazer._gazeTracker.position.z += deltaFighting;
  89572. }
  89573. else {
  89574. gazer._gazeTracker.position.z -= deltaFighting;
  89575. }
  89576. }
  89577. // Changing the size of the laser pointer based on the distance from the targetted point
  89578. gazer._updatePointerDistance(hit.distance);
  89579. }
  89580. else {
  89581. gazer._updatePointerDistance();
  89582. gazer._gazeTracker.isVisible = false;
  89583. }
  89584. if (hit && hit.pickedMesh) {
  89585. // The object selected is the floor, we're in a teleportation scenario
  89586. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89587. // Moving the teleportation area to this targetted point
  89588. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89589. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89590. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89591. }
  89592. gazer._currentMeshSelected = null;
  89593. if (gazer._teleportationRequestInitiated) {
  89594. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89595. }
  89596. return;
  89597. }
  89598. // If not, we're in a selection scenario
  89599. //this._teleportationAllowed = false;
  89600. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89601. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89602. this.onNewMeshPicked.notifyObservers(hit);
  89603. gazer._currentMeshSelected = hit.pickedMesh;
  89604. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89605. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89606. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89607. gazer._isActionableMesh = true;
  89608. }
  89609. else {
  89610. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89611. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89612. gazer._isActionableMesh = false;
  89613. }
  89614. try {
  89615. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89616. }
  89617. catch (err) {
  89618. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89619. }
  89620. }
  89621. else {
  89622. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89623. gazer._currentMeshSelected = null;
  89624. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89625. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89626. }
  89627. }
  89628. }
  89629. else {
  89630. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89631. gazer._currentMeshSelected = null;
  89632. //this._teleportationAllowed = false;
  89633. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89634. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89635. }
  89636. };
  89637. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89638. if (mesh) {
  89639. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89640. }
  89641. };
  89642. /**
  89643. * Sets the color of the laser ray from the vr controllers.
  89644. * @param color new color for the ray.
  89645. */
  89646. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89647. if (this.leftController) {
  89648. this.leftController._setLaserPointerColor(color);
  89649. }
  89650. if (this.rightController) {
  89651. this.rightController._setLaserPointerColor(color);
  89652. }
  89653. };
  89654. /**
  89655. * Sets the color of the ray from the vr headsets gaze.
  89656. * @param color new color for the ray.
  89657. */
  89658. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89659. if (!this._cameraGazer._gazeTracker.material) {
  89660. return;
  89661. }
  89662. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89663. if (this.leftController) {
  89664. this.leftController._gazeTracker.material.emissiveColor = color;
  89665. }
  89666. if (this.rightController) {
  89667. this.rightController._gazeTracker.material.emissiveColor = color;
  89668. }
  89669. };
  89670. /**
  89671. * Exits VR and disposes of the vr experience helper
  89672. */
  89673. VRExperienceHelper.prototype.dispose = function () {
  89674. if (this.isInVRMode) {
  89675. this.exitVR();
  89676. }
  89677. if (this._postProcessMove) {
  89678. this._postProcessMove.dispose();
  89679. }
  89680. if (this._webVRCamera) {
  89681. this._webVRCamera.dispose();
  89682. }
  89683. if (this._vrDeviceOrientationCamera) {
  89684. this._vrDeviceOrientationCamera.dispose();
  89685. }
  89686. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89687. document.body.removeChild(this._btnVR);
  89688. }
  89689. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89690. this._deviceOrientationCamera.dispose();
  89691. }
  89692. if (this._cameraGazer) {
  89693. this._cameraGazer.dispose();
  89694. }
  89695. if (this.leftController) {
  89696. this.leftController.dispose();
  89697. }
  89698. if (this.rightController) {
  89699. this.rightController.dispose();
  89700. }
  89701. if (this._teleportationTarget) {
  89702. this._teleportationTarget.dispose();
  89703. }
  89704. this._floorMeshesCollection = [];
  89705. document.removeEventListener("keydown", this._onKeyDown);
  89706. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89707. window.removeEventListener("resize", this._onResize);
  89708. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89709. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89710. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89711. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89712. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89713. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89714. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89715. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89716. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89717. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89718. this._scene.unregisterBeforeRender(this.beforeRender);
  89719. };
  89720. /**
  89721. * Gets the name of the VRExperienceHelper class
  89722. * @returns "VRExperienceHelper"
  89723. */
  89724. VRExperienceHelper.prototype.getClassName = function () {
  89725. return "VRExperienceHelper";
  89726. };
  89727. return VRExperienceHelper;
  89728. }());
  89729. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89730. })(BABYLON || (BABYLON = {}));
  89731. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89732. // Mainly based on these 2 articles :
  89733. // 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
  89734. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89735. var BABYLON;
  89736. (function (BABYLON) {
  89737. /**
  89738. * Defines the potential axis of a Joystick
  89739. */
  89740. var JoystickAxis;
  89741. (function (JoystickAxis) {
  89742. /** X axis */
  89743. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89744. /** Y axis */
  89745. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89746. /** Z axis */
  89747. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89748. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89749. /**
  89750. * Class used to define virtual joystick (used in touch mode)
  89751. */
  89752. var VirtualJoystick = /** @class */ (function () {
  89753. /**
  89754. * Creates a new virtual joystick
  89755. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89756. */
  89757. function VirtualJoystick(leftJoystick) {
  89758. var _this = this;
  89759. if (leftJoystick) {
  89760. this._leftJoystick = true;
  89761. }
  89762. else {
  89763. this._leftJoystick = false;
  89764. }
  89765. VirtualJoystick._globalJoystickIndex++;
  89766. // By default left & right arrow keys are moving the X
  89767. // and up & down keys are moving the Y
  89768. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89769. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89770. this.reverseLeftRight = false;
  89771. this.reverseUpDown = false;
  89772. // collections of pointers
  89773. this._touches = new BABYLON.StringDictionary();
  89774. this.deltaPosition = BABYLON.Vector3.Zero();
  89775. this._joystickSensibility = 25;
  89776. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89777. this._onResize = function (evt) {
  89778. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89779. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89780. if (VirtualJoystick.vjCanvas) {
  89781. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89782. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89783. }
  89784. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89785. };
  89786. // injecting a canvas element on top of the canvas 3D game
  89787. if (!VirtualJoystick.vjCanvas) {
  89788. window.addEventListener("resize", this._onResize, false);
  89789. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89790. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89791. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89792. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89793. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89794. VirtualJoystick.vjCanvas.style.width = "100%";
  89795. VirtualJoystick.vjCanvas.style.height = "100%";
  89796. VirtualJoystick.vjCanvas.style.position = "absolute";
  89797. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89798. VirtualJoystick.vjCanvas.style.top = "0px";
  89799. VirtualJoystick.vjCanvas.style.left = "0px";
  89800. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89801. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89802. // Support for jQuery PEP polyfill
  89803. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89804. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89805. if (!context) {
  89806. throw new Error("Unable to create canvas for virtual joystick");
  89807. }
  89808. VirtualJoystick.vjCanvasContext = context;
  89809. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89810. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89811. document.body.appendChild(VirtualJoystick.vjCanvas);
  89812. }
  89813. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89814. this.pressed = false;
  89815. // default joystick color
  89816. this._joystickColor = "cyan";
  89817. this._joystickPointerID = -1;
  89818. // current joystick position
  89819. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89820. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89821. // origin joystick position
  89822. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89823. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89824. this._onPointerDownHandlerRef = function (evt) {
  89825. _this._onPointerDown(evt);
  89826. };
  89827. this._onPointerMoveHandlerRef = function (evt) {
  89828. _this._onPointerMove(evt);
  89829. };
  89830. this._onPointerUpHandlerRef = function (evt) {
  89831. _this._onPointerUp(evt);
  89832. };
  89833. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89834. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89835. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89836. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89837. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89838. evt.preventDefault(); // Disables system menu
  89839. }, false);
  89840. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89841. }
  89842. /**
  89843. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89844. * @param newJoystickSensibility defines the new sensibility
  89845. */
  89846. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89847. this._joystickSensibility = newJoystickSensibility;
  89848. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89849. };
  89850. VirtualJoystick.prototype._onPointerDown = function (e) {
  89851. var positionOnScreenCondition;
  89852. e.preventDefault();
  89853. if (this._leftJoystick === true) {
  89854. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89855. }
  89856. else {
  89857. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89858. }
  89859. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89860. // First contact will be dedicated to the virtual joystick
  89861. this._joystickPointerID = e.pointerId;
  89862. this._joystickPointerStartPos.x = e.clientX;
  89863. this._joystickPointerStartPos.y = e.clientY;
  89864. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89865. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89866. this._deltaJoystickVector.x = 0;
  89867. this._deltaJoystickVector.y = 0;
  89868. this.pressed = true;
  89869. this._touches.add(e.pointerId.toString(), e);
  89870. }
  89871. else {
  89872. // You can only trigger the action buttons with a joystick declared
  89873. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89874. this._action();
  89875. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89876. }
  89877. }
  89878. };
  89879. VirtualJoystick.prototype._onPointerMove = function (e) {
  89880. // If the current pointer is the one associated to the joystick (first touch contact)
  89881. if (this._joystickPointerID == e.pointerId) {
  89882. this._joystickPointerPos.x = e.clientX;
  89883. this._joystickPointerPos.y = e.clientY;
  89884. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89885. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89886. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89887. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89888. switch (this._axisTargetedByLeftAndRight) {
  89889. case JoystickAxis.X:
  89890. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89891. break;
  89892. case JoystickAxis.Y:
  89893. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89894. break;
  89895. case JoystickAxis.Z:
  89896. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89897. break;
  89898. }
  89899. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89900. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89901. switch (this._axisTargetedByUpAndDown) {
  89902. case JoystickAxis.X:
  89903. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89904. break;
  89905. case JoystickAxis.Y:
  89906. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89907. break;
  89908. case JoystickAxis.Z:
  89909. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89910. break;
  89911. }
  89912. }
  89913. else {
  89914. var data = this._touches.get(e.pointerId.toString());
  89915. if (data) {
  89916. data.x = e.clientX;
  89917. data.y = e.clientY;
  89918. }
  89919. }
  89920. };
  89921. VirtualJoystick.prototype._onPointerUp = function (e) {
  89922. if (this._joystickPointerID == e.pointerId) {
  89923. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89924. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89925. this._joystickPointerID = -1;
  89926. this.pressed = false;
  89927. }
  89928. else {
  89929. var touch = this._touches.get(e.pointerId.toString());
  89930. if (touch) {
  89931. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89932. }
  89933. }
  89934. this._deltaJoystickVector.x = 0;
  89935. this._deltaJoystickVector.y = 0;
  89936. this._touches.remove(e.pointerId.toString());
  89937. };
  89938. /**
  89939. * Change the color of the virtual joystick
  89940. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89941. */
  89942. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89943. this._joystickColor = newColor;
  89944. };
  89945. /**
  89946. * Defines a callback to call when the joystick is touched
  89947. * @param action defines the callback
  89948. */
  89949. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89950. this._action = action;
  89951. };
  89952. /**
  89953. * Defines which axis you'd like to control for left & right
  89954. * @param axis defines the axis to use
  89955. */
  89956. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89957. switch (axis) {
  89958. case JoystickAxis.X:
  89959. case JoystickAxis.Y:
  89960. case JoystickAxis.Z:
  89961. this._axisTargetedByLeftAndRight = axis;
  89962. break;
  89963. default:
  89964. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89965. break;
  89966. }
  89967. };
  89968. /**
  89969. * Defines which axis you'd like to control for up & down
  89970. * @param axis defines the axis to use
  89971. */
  89972. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89973. switch (axis) {
  89974. case JoystickAxis.X:
  89975. case JoystickAxis.Y:
  89976. case JoystickAxis.Z:
  89977. this._axisTargetedByUpAndDown = axis;
  89978. break;
  89979. default:
  89980. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89981. break;
  89982. }
  89983. };
  89984. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89985. var _this = this;
  89986. if (this.pressed) {
  89987. this._touches.forEach(function (key, touch) {
  89988. if (touch.pointerId === _this._joystickPointerID) {
  89989. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89990. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89991. VirtualJoystick.vjCanvasContext.beginPath();
  89992. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89993. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89994. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89995. VirtualJoystick.vjCanvasContext.stroke();
  89996. VirtualJoystick.vjCanvasContext.closePath();
  89997. VirtualJoystick.vjCanvasContext.beginPath();
  89998. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89999. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  90000. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  90001. VirtualJoystick.vjCanvasContext.stroke();
  90002. VirtualJoystick.vjCanvasContext.closePath();
  90003. VirtualJoystick.vjCanvasContext.beginPath();
  90004. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90005. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  90006. VirtualJoystick.vjCanvasContext.stroke();
  90007. VirtualJoystick.vjCanvasContext.closePath();
  90008. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  90009. }
  90010. else {
  90011. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90012. VirtualJoystick.vjCanvasContext.beginPath();
  90013. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  90014. VirtualJoystick.vjCanvasContext.beginPath();
  90015. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  90016. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90017. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  90018. VirtualJoystick.vjCanvasContext.stroke();
  90019. VirtualJoystick.vjCanvasContext.closePath();
  90020. touch.prevX = touch.x;
  90021. touch.prevY = touch.y;
  90022. }
  90023. ;
  90024. });
  90025. }
  90026. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  90027. };
  90028. /**
  90029. * Release internal HTML canvas
  90030. */
  90031. VirtualJoystick.prototype.releaseCanvas = function () {
  90032. if (VirtualJoystick.vjCanvas) {
  90033. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  90034. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  90035. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  90036. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  90037. window.removeEventListener("resize", this._onResize);
  90038. document.body.removeChild(VirtualJoystick.vjCanvas);
  90039. VirtualJoystick.vjCanvas = null;
  90040. }
  90041. };
  90042. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  90043. VirtualJoystick._globalJoystickIndex = 0;
  90044. return VirtualJoystick;
  90045. }());
  90046. BABYLON.VirtualJoystick = VirtualJoystick;
  90047. })(BABYLON || (BABYLON = {}));
  90048. //# sourceMappingURL=babylon.virtualJoystick.js.map
  90049. var BABYLON;
  90050. (function (BABYLON) {
  90051. // We're mainly based on the logic defined into the FreeCamera code
  90052. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  90053. __extends(VirtualJoysticksCamera, _super);
  90054. function VirtualJoysticksCamera(name, position, scene) {
  90055. var _this = _super.call(this, name, position, scene) || this;
  90056. _this.inputs.addVirtualJoystick();
  90057. return _this;
  90058. }
  90059. VirtualJoysticksCamera.prototype.getClassName = function () {
  90060. return "VirtualJoysticksCamera";
  90061. };
  90062. return VirtualJoysticksCamera;
  90063. }(BABYLON.FreeCamera));
  90064. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  90065. })(BABYLON || (BABYLON = {}));
  90066. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  90067. var BABYLON;
  90068. (function (BABYLON) {
  90069. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  90070. function FreeCameraVirtualJoystickInput() {
  90071. }
  90072. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  90073. return this._leftjoystick;
  90074. };
  90075. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  90076. return this._rightjoystick;
  90077. };
  90078. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  90079. if (this._leftjoystick) {
  90080. var camera = this.camera;
  90081. var speed = camera._computeLocalCameraSpeed() * 50;
  90082. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  90083. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  90084. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  90085. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  90086. if (!this._leftjoystick.pressed) {
  90087. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  90088. }
  90089. if (!this._rightjoystick.pressed) {
  90090. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  90091. }
  90092. }
  90093. };
  90094. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  90095. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  90096. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  90097. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  90098. this._leftjoystick.setJoystickSensibility(0.15);
  90099. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  90100. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  90101. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  90102. this._rightjoystick.reverseUpDown = true;
  90103. this._rightjoystick.setJoystickSensibility(0.05);
  90104. this._rightjoystick.setJoystickColor("yellow");
  90105. };
  90106. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  90107. this._leftjoystick.releaseCanvas();
  90108. this._rightjoystick.releaseCanvas();
  90109. };
  90110. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  90111. return "FreeCameraVirtualJoystickInput";
  90112. };
  90113. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  90114. return "virtualJoystick";
  90115. };
  90116. return FreeCameraVirtualJoystickInput;
  90117. }());
  90118. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  90119. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  90120. })(BABYLON || (BABYLON = {}));
  90121. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  90122. var BABYLON;
  90123. (function (BABYLON) {
  90124. var SimplificationSettings = /** @class */ (function () {
  90125. function SimplificationSettings(quality, distance, optimizeMesh) {
  90126. this.quality = quality;
  90127. this.distance = distance;
  90128. this.optimizeMesh = optimizeMesh;
  90129. }
  90130. return SimplificationSettings;
  90131. }());
  90132. BABYLON.SimplificationSettings = SimplificationSettings;
  90133. var SimplificationQueue = /** @class */ (function () {
  90134. function SimplificationQueue() {
  90135. this.running = false;
  90136. this._simplificationArray = [];
  90137. }
  90138. SimplificationQueue.prototype.addTask = function (task) {
  90139. this._simplificationArray.push(task);
  90140. };
  90141. SimplificationQueue.prototype.executeNext = function () {
  90142. var task = this._simplificationArray.pop();
  90143. if (task) {
  90144. this.running = true;
  90145. this.runSimplification(task);
  90146. }
  90147. else {
  90148. this.running = false;
  90149. }
  90150. };
  90151. SimplificationQueue.prototype.runSimplification = function (task) {
  90152. var _this = this;
  90153. if (task.parallelProcessing) {
  90154. //parallel simplifier
  90155. task.settings.forEach(function (setting) {
  90156. var simplifier = _this.getSimplifier(task);
  90157. simplifier.simplify(setting, function (newMesh) {
  90158. task.mesh.addLODLevel(setting.distance, newMesh);
  90159. newMesh.isVisible = true;
  90160. //check if it is the last
  90161. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  90162. //all done, run the success callback.
  90163. task.successCallback();
  90164. }
  90165. _this.executeNext();
  90166. });
  90167. });
  90168. }
  90169. else {
  90170. //single simplifier.
  90171. var simplifier = this.getSimplifier(task);
  90172. var runDecimation = function (setting, callback) {
  90173. simplifier.simplify(setting, function (newMesh) {
  90174. task.mesh.addLODLevel(setting.distance, newMesh);
  90175. newMesh.isVisible = true;
  90176. //run the next quality level
  90177. callback();
  90178. });
  90179. };
  90180. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  90181. runDecimation(task.settings[loop.index], function () {
  90182. loop.executeNext();
  90183. });
  90184. }, function () {
  90185. //execution ended, run the success callback.
  90186. if (task.successCallback) {
  90187. task.successCallback();
  90188. }
  90189. _this.executeNext();
  90190. });
  90191. }
  90192. };
  90193. SimplificationQueue.prototype.getSimplifier = function (task) {
  90194. switch (task.simplificationType) {
  90195. case SimplificationType.QUADRATIC:
  90196. default:
  90197. return new QuadraticErrorSimplification(task.mesh);
  90198. }
  90199. };
  90200. return SimplificationQueue;
  90201. }());
  90202. BABYLON.SimplificationQueue = SimplificationQueue;
  90203. /**
  90204. * The implemented types of simplification
  90205. * At the moment only Quadratic Error Decimation is implemented
  90206. */
  90207. var SimplificationType;
  90208. (function (SimplificationType) {
  90209. /** Quadratic error decimation */
  90210. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  90211. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  90212. var DecimationTriangle = /** @class */ (function () {
  90213. function DecimationTriangle(vertices) {
  90214. this.vertices = vertices;
  90215. this.error = new Array(4);
  90216. this.deleted = false;
  90217. this.isDirty = false;
  90218. this.deletePending = false;
  90219. this.borderFactor = 0;
  90220. }
  90221. return DecimationTriangle;
  90222. }());
  90223. BABYLON.DecimationTriangle = DecimationTriangle;
  90224. var DecimationVertex = /** @class */ (function () {
  90225. function DecimationVertex(position, id) {
  90226. this.position = position;
  90227. this.id = id;
  90228. this.isBorder = true;
  90229. this.q = new QuadraticMatrix();
  90230. this.triangleCount = 0;
  90231. this.triangleStart = 0;
  90232. this.originalOffsets = [];
  90233. }
  90234. DecimationVertex.prototype.updatePosition = function (newPosition) {
  90235. this.position.copyFrom(newPosition);
  90236. };
  90237. return DecimationVertex;
  90238. }());
  90239. BABYLON.DecimationVertex = DecimationVertex;
  90240. var QuadraticMatrix = /** @class */ (function () {
  90241. function QuadraticMatrix(data) {
  90242. this.data = new Array(10);
  90243. for (var i = 0; i < 10; ++i) {
  90244. if (data && data[i]) {
  90245. this.data[i] = data[i];
  90246. }
  90247. else {
  90248. this.data[i] = 0;
  90249. }
  90250. }
  90251. }
  90252. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  90253. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  90254. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  90255. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  90256. return det;
  90257. };
  90258. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  90259. for (var i = 0; i < 10; ++i) {
  90260. this.data[i] += matrix.data[i];
  90261. }
  90262. };
  90263. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  90264. for (var i = 0; i < 10; ++i) {
  90265. this.data[i] += data[i];
  90266. }
  90267. };
  90268. QuadraticMatrix.prototype.add = function (matrix) {
  90269. var m = new QuadraticMatrix();
  90270. for (var i = 0; i < 10; ++i) {
  90271. m.data[i] = this.data[i] + matrix.data[i];
  90272. }
  90273. return m;
  90274. };
  90275. QuadraticMatrix.FromData = function (a, b, c, d) {
  90276. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  90277. };
  90278. //returning an array to avoid garbage collection
  90279. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  90280. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  90281. };
  90282. return QuadraticMatrix;
  90283. }());
  90284. BABYLON.QuadraticMatrix = QuadraticMatrix;
  90285. var Reference = /** @class */ (function () {
  90286. function Reference(vertexId, triangleId) {
  90287. this.vertexId = vertexId;
  90288. this.triangleId = triangleId;
  90289. }
  90290. return Reference;
  90291. }());
  90292. BABYLON.Reference = Reference;
  90293. /**
  90294. * An implementation of the Quadratic Error simplification algorithm.
  90295. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  90296. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  90297. * @author RaananW
  90298. */
  90299. var QuadraticErrorSimplification = /** @class */ (function () {
  90300. function QuadraticErrorSimplification(_mesh) {
  90301. this._mesh = _mesh;
  90302. this.syncIterations = 5000;
  90303. this.aggressiveness = 7;
  90304. this.decimationIterations = 100;
  90305. this.boundingBoxEpsilon = BABYLON.Epsilon;
  90306. }
  90307. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  90308. var _this = this;
  90309. this.initDecimatedMesh();
  90310. //iterating through the submeshes array, one after the other.
  90311. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  90312. _this.initWithMesh(loop.index, function () {
  90313. _this.runDecimation(settings, loop.index, function () {
  90314. loop.executeNext();
  90315. });
  90316. }, settings.optimizeMesh);
  90317. }, function () {
  90318. setTimeout(function () {
  90319. successCallback(_this._reconstructedMesh);
  90320. }, 0);
  90321. });
  90322. };
  90323. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  90324. var _this = this;
  90325. var targetCount = ~~(this.triangles.length * settings.quality);
  90326. var deletedTriangles = 0;
  90327. var triangleCount = this.triangles.length;
  90328. var iterationFunction = function (iteration, callback) {
  90329. setTimeout(function () {
  90330. if (iteration % 5 === 0) {
  90331. _this.updateMesh(iteration === 0);
  90332. }
  90333. for (var i = 0; i < _this.triangles.length; ++i) {
  90334. _this.triangles[i].isDirty = false;
  90335. }
  90336. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  90337. var trianglesIterator = function (i) {
  90338. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  90339. var t = _this.triangles[tIdx];
  90340. if (!t)
  90341. return;
  90342. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  90343. return;
  90344. }
  90345. for (var j = 0; j < 3; ++j) {
  90346. if (t.error[j] < threshold) {
  90347. var deleted0 = [];
  90348. var deleted1 = [];
  90349. var v0 = t.vertices[j];
  90350. var v1 = t.vertices[(j + 1) % 3];
  90351. if (v0.isBorder || v1.isBorder)
  90352. continue;
  90353. var p = BABYLON.Vector3.Zero();
  90354. var n = BABYLON.Vector3.Zero();
  90355. var uv = BABYLON.Vector2.Zero();
  90356. var color = new BABYLON.Color4(0, 0, 0, 1);
  90357. _this.calculateError(v0, v1, p, n, uv, color);
  90358. var delTr = new Array();
  90359. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  90360. continue;
  90361. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  90362. continue;
  90363. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  90364. continue;
  90365. var uniqueArray = new Array();
  90366. delTr.forEach(function (deletedT) {
  90367. if (uniqueArray.indexOf(deletedT) === -1) {
  90368. deletedT.deletePending = true;
  90369. uniqueArray.push(deletedT);
  90370. }
  90371. });
  90372. if (uniqueArray.length % 2 !== 0) {
  90373. continue;
  90374. }
  90375. v0.q = v1.q.add(v0.q);
  90376. v0.updatePosition(p);
  90377. var tStart = _this.references.length;
  90378. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  90379. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  90380. var tCount = _this.references.length - tStart;
  90381. if (tCount <= v0.triangleCount) {
  90382. if (tCount) {
  90383. for (var c = 0; c < tCount; c++) {
  90384. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  90385. }
  90386. }
  90387. }
  90388. else {
  90389. v0.triangleStart = tStart;
  90390. }
  90391. v0.triangleCount = tCount;
  90392. break;
  90393. }
  90394. }
  90395. };
  90396. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  90397. }, 0);
  90398. };
  90399. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  90400. if (triangleCount - deletedTriangles <= targetCount)
  90401. loop.breakLoop();
  90402. else {
  90403. iterationFunction(loop.index, function () {
  90404. loop.executeNext();
  90405. });
  90406. }
  90407. }, function () {
  90408. setTimeout(function () {
  90409. //reconstruct this part of the mesh
  90410. _this.reconstructMesh(submeshIndex);
  90411. successCallback();
  90412. }, 0);
  90413. });
  90414. };
  90415. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  90416. var _this = this;
  90417. this.vertices = [];
  90418. this.triangles = [];
  90419. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90420. var indices = this._mesh.getIndices();
  90421. var submesh = this._mesh.subMeshes[submeshIndex];
  90422. var findInVertices = function (positionToSearch) {
  90423. if (optimizeMesh) {
  90424. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  90425. if (_this.vertices[ii].position.equals(positionToSearch)) {
  90426. return _this.vertices[ii];
  90427. }
  90428. }
  90429. }
  90430. return null;
  90431. };
  90432. var vertexReferences = [];
  90433. var vertexInit = function (i) {
  90434. if (!positionData) {
  90435. return;
  90436. }
  90437. var offset = i + submesh.verticesStart;
  90438. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  90439. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  90440. vertex.originalOffsets.push(offset);
  90441. if (vertex.id === _this.vertices.length) {
  90442. _this.vertices.push(vertex);
  90443. }
  90444. vertexReferences.push(vertex.id);
  90445. };
  90446. //var totalVertices = mesh.getTotalVertices();
  90447. var totalVertices = submesh.verticesCount;
  90448. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  90449. var indicesInit = function (i) {
  90450. if (!indices) {
  90451. return;
  90452. }
  90453. var offset = (submesh.indexStart / 3) + i;
  90454. var pos = (offset * 3);
  90455. var i0 = indices[pos + 0];
  90456. var i1 = indices[pos + 1];
  90457. var i2 = indices[pos + 2];
  90458. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  90459. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  90460. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  90461. var triangle = new DecimationTriangle([v0, v1, v2]);
  90462. triangle.originalOffset = pos;
  90463. _this.triangles.push(triangle);
  90464. };
  90465. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  90466. _this.init(callback);
  90467. });
  90468. });
  90469. };
  90470. QuadraticErrorSimplification.prototype.init = function (callback) {
  90471. var _this = this;
  90472. var triangleInit1 = function (i) {
  90473. var t = _this.triangles[i];
  90474. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  90475. for (var j = 0; j < 3; j++) {
  90476. 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))));
  90477. }
  90478. };
  90479. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  90480. var triangleInit2 = function (i) {
  90481. var t = _this.triangles[i];
  90482. for (var j = 0; j < 3; ++j) {
  90483. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  90484. }
  90485. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90486. };
  90487. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  90488. callback();
  90489. });
  90490. });
  90491. };
  90492. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  90493. var newTriangles = [];
  90494. var i;
  90495. for (i = 0; i < this.vertices.length; ++i) {
  90496. this.vertices[i].triangleCount = 0;
  90497. }
  90498. var t;
  90499. var j;
  90500. for (i = 0; i < this.triangles.length; ++i) {
  90501. if (!this.triangles[i].deleted) {
  90502. t = this.triangles[i];
  90503. for (j = 0; j < 3; ++j) {
  90504. t.vertices[j].triangleCount = 1;
  90505. }
  90506. newTriangles.push(t);
  90507. }
  90508. }
  90509. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  90510. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  90511. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  90512. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  90513. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  90514. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90515. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  90516. var vertexCount = 0;
  90517. for (i = 0; i < this.vertices.length; ++i) {
  90518. var vertex = this.vertices[i];
  90519. vertex.id = vertexCount;
  90520. if (vertex.triangleCount) {
  90521. vertex.originalOffsets.forEach(function (originalOffset) {
  90522. if (!normalData) {
  90523. return;
  90524. }
  90525. newPositionData.push(vertex.position.x);
  90526. newPositionData.push(vertex.position.y);
  90527. newPositionData.push(vertex.position.z);
  90528. newNormalData.push(normalData[originalOffset * 3]);
  90529. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  90530. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  90531. if (uvs && uvs.length) {
  90532. newUVsData.push(uvs[(originalOffset * 2)]);
  90533. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90534. }
  90535. else if (colorsData && colorsData.length) {
  90536. newColorsData.push(colorsData[(originalOffset * 4)]);
  90537. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90538. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90539. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90540. }
  90541. ++vertexCount;
  90542. });
  90543. }
  90544. }
  90545. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90546. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90547. var submeshesArray = this._reconstructedMesh.subMeshes;
  90548. this._reconstructedMesh.subMeshes = [];
  90549. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90550. var originalIndices = this._mesh.getIndices();
  90551. for (i = 0; i < newTriangles.length; ++i) {
  90552. t = newTriangles[i]; //now get the new referencing point for each vertex
  90553. [0, 1, 2].forEach(function (idx) {
  90554. var id = originalIndices[t.originalOffset + idx];
  90555. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90556. if (offset < 0)
  90557. offset = 0;
  90558. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90559. });
  90560. }
  90561. //overwriting the old vertex buffers and indices.
  90562. this._reconstructedMesh.setIndices(newIndicesArray);
  90563. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90564. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90565. if (newUVsData.length > 0)
  90566. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90567. if (newColorsData.length > 0)
  90568. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90569. //create submesh
  90570. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90571. if (submeshIndex > 0) {
  90572. this._reconstructedMesh.subMeshes = [];
  90573. submeshesArray.forEach(function (submesh) {
  90574. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90575. });
  90576. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90577. }
  90578. };
  90579. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90580. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90581. this._reconstructedMesh.material = this._mesh.material;
  90582. this._reconstructedMesh.parent = this._mesh.parent;
  90583. this._reconstructedMesh.isVisible = false;
  90584. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90585. };
  90586. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90587. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90588. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90589. if (t.deleted)
  90590. continue;
  90591. var s = this.references[vertex1.triangleStart + i].vertexId;
  90592. var v1 = t.vertices[(s + 1) % 3];
  90593. var v2 = t.vertices[(s + 2) % 3];
  90594. if ((v1 === vertex2 || v2 === vertex2)) {
  90595. deletedArray[i] = true;
  90596. delTr.push(t);
  90597. continue;
  90598. }
  90599. var d1 = v1.position.subtract(point);
  90600. d1 = d1.normalize();
  90601. var d2 = v2.position.subtract(point);
  90602. d2 = d2.normalize();
  90603. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90604. return true;
  90605. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90606. deletedArray[i] = false;
  90607. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90608. return true;
  90609. }
  90610. return false;
  90611. };
  90612. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90613. var newDeleted = deletedTriangles;
  90614. for (var i = 0; i < vertex.triangleCount; ++i) {
  90615. var ref = this.references[vertex.triangleStart + i];
  90616. var t = this.triangles[ref.triangleId];
  90617. if (t.deleted)
  90618. continue;
  90619. if (deletedArray[i] && t.deletePending) {
  90620. t.deleted = true;
  90621. newDeleted++;
  90622. continue;
  90623. }
  90624. t.vertices[ref.vertexId] = origVertex;
  90625. t.isDirty = true;
  90626. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90627. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90628. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90629. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90630. this.references.push(ref);
  90631. }
  90632. return newDeleted;
  90633. };
  90634. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90635. for (var i = 0; i < this.vertices.length; ++i) {
  90636. var vCount = [];
  90637. var vId = [];
  90638. var v = this.vertices[i];
  90639. var j;
  90640. for (j = 0; j < v.triangleCount; ++j) {
  90641. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90642. for (var ii = 0; ii < 3; ii++) {
  90643. var ofs = 0;
  90644. var vv = triangle.vertices[ii];
  90645. while (ofs < vCount.length) {
  90646. if (vId[ofs] === vv.id)
  90647. break;
  90648. ++ofs;
  90649. }
  90650. if (ofs === vCount.length) {
  90651. vCount.push(1);
  90652. vId.push(vv.id);
  90653. }
  90654. else {
  90655. vCount[ofs]++;
  90656. }
  90657. }
  90658. }
  90659. for (j = 0; j < vCount.length; ++j) {
  90660. if (vCount[j] === 1) {
  90661. this.vertices[vId[j]].isBorder = true;
  90662. }
  90663. else {
  90664. this.vertices[vId[j]].isBorder = false;
  90665. }
  90666. }
  90667. }
  90668. };
  90669. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90670. if (identifyBorders === void 0) { identifyBorders = false; }
  90671. var i;
  90672. if (!identifyBorders) {
  90673. var newTrianglesVector = [];
  90674. for (i = 0; i < this.triangles.length; ++i) {
  90675. if (!this.triangles[i].deleted) {
  90676. newTrianglesVector.push(this.triangles[i]);
  90677. }
  90678. }
  90679. this.triangles = newTrianglesVector;
  90680. }
  90681. for (i = 0; i < this.vertices.length; ++i) {
  90682. this.vertices[i].triangleCount = 0;
  90683. this.vertices[i].triangleStart = 0;
  90684. }
  90685. var t;
  90686. var j;
  90687. var v;
  90688. for (i = 0; i < this.triangles.length; ++i) {
  90689. t = this.triangles[i];
  90690. for (j = 0; j < 3; ++j) {
  90691. v = t.vertices[j];
  90692. v.triangleCount++;
  90693. }
  90694. }
  90695. var tStart = 0;
  90696. for (i = 0; i < this.vertices.length; ++i) {
  90697. this.vertices[i].triangleStart = tStart;
  90698. tStart += this.vertices[i].triangleCount;
  90699. this.vertices[i].triangleCount = 0;
  90700. }
  90701. var newReferences = new Array(this.triangles.length * 3);
  90702. for (i = 0; i < this.triangles.length; ++i) {
  90703. t = this.triangles[i];
  90704. for (j = 0; j < 3; ++j) {
  90705. v = t.vertices[j];
  90706. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90707. v.triangleCount++;
  90708. }
  90709. }
  90710. this.references = newReferences;
  90711. if (identifyBorders) {
  90712. this.identifyBorder();
  90713. }
  90714. };
  90715. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90716. var x = point.x;
  90717. var y = point.y;
  90718. var z = point.z;
  90719. 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
  90720. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90721. };
  90722. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90723. var q = vertex1.q.add(vertex2.q);
  90724. var border = vertex1.isBorder && vertex2.isBorder;
  90725. var error = 0;
  90726. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90727. if (qDet !== 0 && !border) {
  90728. if (!pointResult) {
  90729. pointResult = BABYLON.Vector3.Zero();
  90730. }
  90731. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90732. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90733. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90734. error = this.vertexError(q, pointResult);
  90735. }
  90736. else {
  90737. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90738. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90739. var error1 = this.vertexError(q, vertex1.position);
  90740. var error2 = this.vertexError(q, vertex2.position);
  90741. var error3 = this.vertexError(q, p3);
  90742. error = Math.min(error1, error2, error3);
  90743. if (error === error1) {
  90744. if (pointResult) {
  90745. pointResult.copyFrom(vertex1.position);
  90746. }
  90747. }
  90748. else if (error === error2) {
  90749. if (pointResult) {
  90750. pointResult.copyFrom(vertex2.position);
  90751. }
  90752. }
  90753. else {
  90754. if (pointResult) {
  90755. pointResult.copyFrom(p3);
  90756. }
  90757. }
  90758. }
  90759. return error;
  90760. };
  90761. return QuadraticErrorSimplification;
  90762. }());
  90763. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90764. })(BABYLON || (BABYLON = {}));
  90765. //# sourceMappingURL=babylon.meshSimplification.js.map
  90766. var BABYLON;
  90767. (function (BABYLON) {
  90768. var MeshLODLevel = /** @class */ (function () {
  90769. function MeshLODLevel(distance, mesh) {
  90770. this.distance = distance;
  90771. this.mesh = mesh;
  90772. }
  90773. return MeshLODLevel;
  90774. }());
  90775. BABYLON.MeshLODLevel = MeshLODLevel;
  90776. })(BABYLON || (BABYLON = {}));
  90777. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90778. var BABYLON;
  90779. (function (BABYLON) {
  90780. /**
  90781. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90782. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90783. */
  90784. var SceneOptimization = /** @class */ (function () {
  90785. /**
  90786. * Creates the SceneOptimization object
  90787. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90788. * @param desc defines the description associated with the optimization
  90789. */
  90790. function SceneOptimization(
  90791. /**
  90792. * Defines the priority of this optimization (0 by default which means first in the list)
  90793. */
  90794. priority) {
  90795. if (priority === void 0) { priority = 0; }
  90796. this.priority = priority;
  90797. }
  90798. /**
  90799. * Gets a string describing the action executed by the current optimization
  90800. * @returns description string
  90801. */
  90802. SceneOptimization.prototype.getDescription = function () {
  90803. return "";
  90804. };
  90805. /**
  90806. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90807. * @param scene defines the current scene where to apply this optimization
  90808. * @param optimizer defines the current optimizer
  90809. * @returns true if everything that can be done was applied
  90810. */
  90811. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90812. return true;
  90813. };
  90814. ;
  90815. return SceneOptimization;
  90816. }());
  90817. BABYLON.SceneOptimization = SceneOptimization;
  90818. /**
  90819. * Defines an optimization used to reduce the size of render target textures
  90820. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90821. */
  90822. var TextureOptimization = /** @class */ (function (_super) {
  90823. __extends(TextureOptimization, _super);
  90824. /**
  90825. * Creates the TextureOptimization object
  90826. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90827. * @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
  90828. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90829. */
  90830. function TextureOptimization(
  90831. /**
  90832. * Defines the priority of this optimization (0 by default which means first in the list)
  90833. */
  90834. priority,
  90835. /**
  90836. * 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
  90837. */
  90838. maximumSize,
  90839. /**
  90840. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90841. */
  90842. step) {
  90843. if (priority === void 0) { priority = 0; }
  90844. if (maximumSize === void 0) { maximumSize = 1024; }
  90845. if (step === void 0) { step = 0.5; }
  90846. var _this = _super.call(this, priority) || this;
  90847. _this.priority = priority;
  90848. _this.maximumSize = maximumSize;
  90849. _this.step = step;
  90850. return _this;
  90851. }
  90852. /**
  90853. * Gets a string describing the action executed by the current optimization
  90854. * @returns description string
  90855. */
  90856. TextureOptimization.prototype.getDescription = function () {
  90857. return "Reducing render target texture size to " + this.maximumSize;
  90858. };
  90859. /**
  90860. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90861. * @param scene defines the current scene where to apply this optimization
  90862. * @param optimizer defines the current optimizer
  90863. * @returns true if everything that can be done was applied
  90864. */
  90865. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90866. var allDone = true;
  90867. for (var index = 0; index < scene.textures.length; index++) {
  90868. var texture = scene.textures[index];
  90869. if (!texture.canRescale || texture.getContext) {
  90870. continue;
  90871. }
  90872. var currentSize = texture.getSize();
  90873. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90874. if (maxDimension > this.maximumSize) {
  90875. texture.scale(this.step);
  90876. allDone = false;
  90877. }
  90878. }
  90879. return allDone;
  90880. };
  90881. return TextureOptimization;
  90882. }(SceneOptimization));
  90883. BABYLON.TextureOptimization = TextureOptimization;
  90884. /**
  90885. * Defines an optimization used to increase or decrease the rendering resolution
  90886. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90887. */
  90888. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90889. __extends(HardwareScalingOptimization, _super);
  90890. /**
  90891. * Creates the HardwareScalingOptimization object
  90892. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90893. * @param maximumScale defines the maximum scale to use (2 by default)
  90894. * @param step defines the step to use between two passes (0.5 by default)
  90895. */
  90896. function HardwareScalingOptimization(
  90897. /**
  90898. * Defines the priority of this optimization (0 by default which means first in the list)
  90899. */
  90900. priority,
  90901. /**
  90902. * Defines the maximum scale to use (2 by default)
  90903. */
  90904. maximumScale,
  90905. /**
  90906. * Defines the step to use between two passes (0.5 by default)
  90907. */
  90908. step) {
  90909. if (priority === void 0) { priority = 0; }
  90910. if (maximumScale === void 0) { maximumScale = 2; }
  90911. if (step === void 0) { step = 0.25; }
  90912. var _this = _super.call(this, priority) || this;
  90913. _this.priority = priority;
  90914. _this.maximumScale = maximumScale;
  90915. _this.step = step;
  90916. _this._currentScale = -1;
  90917. _this._directionOffset = 1;
  90918. return _this;
  90919. }
  90920. /**
  90921. * Gets a string describing the action executed by the current optimization
  90922. * @return description string
  90923. */
  90924. HardwareScalingOptimization.prototype.getDescription = function () {
  90925. return "Setting hardware scaling level to " + this._currentScale;
  90926. };
  90927. /**
  90928. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90929. * @param scene defines the current scene where to apply this optimization
  90930. * @param optimizer defines the current optimizer
  90931. * @returns true if everything that can be done was applied
  90932. */
  90933. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90934. if (this._currentScale === -1) {
  90935. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90936. if (this._currentScale > this.maximumScale) {
  90937. this._directionOffset = -1;
  90938. }
  90939. }
  90940. this._currentScale += this._directionOffset * this.step;
  90941. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90942. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90943. };
  90944. ;
  90945. return HardwareScalingOptimization;
  90946. }(SceneOptimization));
  90947. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90948. /**
  90949. * Defines an optimization used to remove shadows
  90950. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90951. */
  90952. var ShadowsOptimization = /** @class */ (function (_super) {
  90953. __extends(ShadowsOptimization, _super);
  90954. function ShadowsOptimization() {
  90955. return _super !== null && _super.apply(this, arguments) || this;
  90956. }
  90957. /**
  90958. * Gets a string describing the action executed by the current optimization
  90959. * @return description string
  90960. */
  90961. ShadowsOptimization.prototype.getDescription = function () {
  90962. return "Turning shadows on/off";
  90963. };
  90964. /**
  90965. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90966. * @param scene defines the current scene where to apply this optimization
  90967. * @param optimizer defines the current optimizer
  90968. * @returns true if everything that can be done was applied
  90969. */
  90970. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90971. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90972. return true;
  90973. };
  90974. ;
  90975. return ShadowsOptimization;
  90976. }(SceneOptimization));
  90977. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90978. /**
  90979. * Defines an optimization used to turn post-processes off
  90980. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90981. */
  90982. var PostProcessesOptimization = /** @class */ (function (_super) {
  90983. __extends(PostProcessesOptimization, _super);
  90984. function PostProcessesOptimization() {
  90985. return _super !== null && _super.apply(this, arguments) || this;
  90986. }
  90987. /**
  90988. * Gets a string describing the action executed by the current optimization
  90989. * @return description string
  90990. */
  90991. PostProcessesOptimization.prototype.getDescription = function () {
  90992. return "Turning post-processes on/off";
  90993. };
  90994. /**
  90995. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90996. * @param scene defines the current scene where to apply this optimization
  90997. * @param optimizer defines the current optimizer
  90998. * @returns true if everything that can be done was applied
  90999. */
  91000. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  91001. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  91002. return true;
  91003. };
  91004. ;
  91005. return PostProcessesOptimization;
  91006. }(SceneOptimization));
  91007. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  91008. /**
  91009. * Defines an optimization used to turn lens flares off
  91010. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91011. */
  91012. var LensFlaresOptimization = /** @class */ (function (_super) {
  91013. __extends(LensFlaresOptimization, _super);
  91014. function LensFlaresOptimization() {
  91015. return _super !== null && _super.apply(this, arguments) || this;
  91016. }
  91017. /**
  91018. * Gets a string describing the action executed by the current optimization
  91019. * @return description string
  91020. */
  91021. LensFlaresOptimization.prototype.getDescription = function () {
  91022. return "Turning lens flares on/off";
  91023. };
  91024. /**
  91025. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91026. * @param scene defines the current scene where to apply this optimization
  91027. * @param optimizer defines the current optimizer
  91028. * @returns true if everything that can be done was applied
  91029. */
  91030. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  91031. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  91032. return true;
  91033. };
  91034. ;
  91035. return LensFlaresOptimization;
  91036. }(SceneOptimization));
  91037. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  91038. /**
  91039. * Defines an optimization based on user defined callback.
  91040. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91041. */
  91042. var CustomOptimization = /** @class */ (function (_super) {
  91043. __extends(CustomOptimization, _super);
  91044. function CustomOptimization() {
  91045. return _super !== null && _super.apply(this, arguments) || this;
  91046. }
  91047. /**
  91048. * Gets a string describing the action executed by the current optimization
  91049. * @returns description string
  91050. */
  91051. CustomOptimization.prototype.getDescription = function () {
  91052. if (this.onGetDescription) {
  91053. return this.onGetDescription();
  91054. }
  91055. return "Running user defined callback";
  91056. };
  91057. /**
  91058. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91059. * @param scene defines the current scene where to apply this optimization
  91060. * @param optimizer defines the current optimizer
  91061. * @returns true if everything that can be done was applied
  91062. */
  91063. CustomOptimization.prototype.apply = function (scene, optimizer) {
  91064. if (this.onApply) {
  91065. return this.onApply(scene, optimizer);
  91066. }
  91067. return true;
  91068. };
  91069. ;
  91070. return CustomOptimization;
  91071. }(SceneOptimization));
  91072. BABYLON.CustomOptimization = CustomOptimization;
  91073. /**
  91074. * Defines an optimization used to turn particles off
  91075. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91076. */
  91077. var ParticlesOptimization = /** @class */ (function (_super) {
  91078. __extends(ParticlesOptimization, _super);
  91079. function ParticlesOptimization() {
  91080. return _super !== null && _super.apply(this, arguments) || this;
  91081. }
  91082. /**
  91083. * Gets a string describing the action executed by the current optimization
  91084. * @return description string
  91085. */
  91086. ParticlesOptimization.prototype.getDescription = function () {
  91087. return "Turning particles on/off";
  91088. };
  91089. /**
  91090. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91091. * @param scene defines the current scene where to apply this optimization
  91092. * @param optimizer defines the current optimizer
  91093. * @returns true if everything that can be done was applied
  91094. */
  91095. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  91096. scene.particlesEnabled = optimizer.isInImprovementMode;
  91097. return true;
  91098. };
  91099. ;
  91100. return ParticlesOptimization;
  91101. }(SceneOptimization));
  91102. BABYLON.ParticlesOptimization = ParticlesOptimization;
  91103. /**
  91104. * Defines an optimization used to turn render targets off
  91105. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91106. */
  91107. var RenderTargetsOptimization = /** @class */ (function (_super) {
  91108. __extends(RenderTargetsOptimization, _super);
  91109. function RenderTargetsOptimization() {
  91110. return _super !== null && _super.apply(this, arguments) || this;
  91111. }
  91112. /**
  91113. * Gets a string describing the action executed by the current optimization
  91114. * @return description string
  91115. */
  91116. RenderTargetsOptimization.prototype.getDescription = function () {
  91117. return "Turning render targets off";
  91118. };
  91119. /**
  91120. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91121. * @param scene defines the current scene where to apply this optimization
  91122. * @param optimizer defines the current optimizer
  91123. * @returns true if everything that can be done was applied
  91124. */
  91125. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  91126. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  91127. return true;
  91128. };
  91129. ;
  91130. return RenderTargetsOptimization;
  91131. }(SceneOptimization));
  91132. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  91133. /**
  91134. * Defines an optimization used to merge meshes with compatible materials
  91135. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91136. */
  91137. var MergeMeshesOptimization = /** @class */ (function (_super) {
  91138. __extends(MergeMeshesOptimization, _super);
  91139. function MergeMeshesOptimization() {
  91140. var _this = _super !== null && _super.apply(this, arguments) || this;
  91141. _this._canBeMerged = function (abstractMesh) {
  91142. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  91143. return false;
  91144. }
  91145. var mesh = abstractMesh;
  91146. if (!mesh.isVisible || !mesh.isEnabled()) {
  91147. return false;
  91148. }
  91149. if (mesh.instances.length > 0) {
  91150. return false;
  91151. }
  91152. if (mesh.skeleton || mesh.hasLODLevels) {
  91153. return false;
  91154. }
  91155. if (mesh.parent) {
  91156. return false;
  91157. }
  91158. return true;
  91159. };
  91160. return _this;
  91161. }
  91162. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  91163. /**
  91164. * Gets or sets a boolean which defines if optimization octree has to be updated
  91165. */
  91166. get: function () {
  91167. return MergeMeshesOptimization._UpdateSelectionTree;
  91168. },
  91169. /**
  91170. * Gets or sets a boolean which defines if optimization octree has to be updated
  91171. */
  91172. set: function (value) {
  91173. MergeMeshesOptimization._UpdateSelectionTree = value;
  91174. },
  91175. enumerable: true,
  91176. configurable: true
  91177. });
  91178. /**
  91179. * Gets a string describing the action executed by the current optimization
  91180. * @return description string
  91181. */
  91182. MergeMeshesOptimization.prototype.getDescription = function () {
  91183. return "Merging similar meshes together";
  91184. };
  91185. /**
  91186. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91187. * @param scene defines the current scene where to apply this optimization
  91188. * @param optimizer defines the current optimizer
  91189. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  91190. * @returns true if everything that can be done was applied
  91191. */
  91192. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  91193. var globalPool = scene.meshes.slice(0);
  91194. var globalLength = globalPool.length;
  91195. for (var index = 0; index < globalLength; index++) {
  91196. var currentPool = new Array();
  91197. var current = globalPool[index];
  91198. // Checks
  91199. if (!this._canBeMerged(current)) {
  91200. continue;
  91201. }
  91202. currentPool.push(current);
  91203. // Find compatible meshes
  91204. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  91205. var otherMesh = globalPool[subIndex];
  91206. if (!this._canBeMerged(otherMesh)) {
  91207. continue;
  91208. }
  91209. if (otherMesh.material !== current.material) {
  91210. continue;
  91211. }
  91212. if (otherMesh.checkCollisions !== current.checkCollisions) {
  91213. continue;
  91214. }
  91215. currentPool.push(otherMesh);
  91216. globalLength--;
  91217. globalPool.splice(subIndex, 1);
  91218. subIndex--;
  91219. }
  91220. if (currentPool.length < 2) {
  91221. continue;
  91222. }
  91223. // Merge meshes
  91224. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  91225. }
  91226. if (updateSelectionTree != undefined) {
  91227. if (updateSelectionTree) {
  91228. scene.createOrUpdateSelectionOctree();
  91229. }
  91230. }
  91231. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  91232. scene.createOrUpdateSelectionOctree();
  91233. }
  91234. return true;
  91235. };
  91236. ;
  91237. MergeMeshesOptimization._UpdateSelectionTree = false;
  91238. return MergeMeshesOptimization;
  91239. }(SceneOptimization));
  91240. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  91241. /**
  91242. * Defines a list of options used by SceneOptimizer
  91243. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91244. */
  91245. var SceneOptimizerOptions = /** @class */ (function () {
  91246. /**
  91247. * Creates a new list of options used by SceneOptimizer
  91248. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  91249. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  91250. */
  91251. function SceneOptimizerOptions(
  91252. /**
  91253. * Defines the target frame rate to reach (60 by default)
  91254. */
  91255. targetFrameRate,
  91256. /**
  91257. * Defines the interval between two checkes (2000ms by default)
  91258. */
  91259. trackerDuration) {
  91260. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  91261. if (trackerDuration === void 0) { trackerDuration = 2000; }
  91262. this.targetFrameRate = targetFrameRate;
  91263. this.trackerDuration = trackerDuration;
  91264. /**
  91265. * Gets the list of optimizations to apply
  91266. */
  91267. this.optimizations = new Array();
  91268. }
  91269. /**
  91270. * Add a new optimization
  91271. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  91272. * @returns the current SceneOptimizerOptions
  91273. */
  91274. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  91275. this.optimizations.push(optimization);
  91276. return this;
  91277. };
  91278. /**
  91279. * Add a new custom optimization
  91280. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  91281. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  91282. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91283. * @returns the current SceneOptimizerOptions
  91284. */
  91285. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  91286. if (priority === void 0) { priority = 0; }
  91287. var optimization = new CustomOptimization(priority);
  91288. optimization.onApply = onApply;
  91289. optimization.onGetDescription = onGetDescription;
  91290. this.optimizations.push(optimization);
  91291. return this;
  91292. };
  91293. /**
  91294. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  91295. * @param targetFrameRate defines the target frame rate (60 by default)
  91296. * @returns a SceneOptimizerOptions object
  91297. */
  91298. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  91299. var result = new SceneOptimizerOptions(targetFrameRate);
  91300. var priority = 0;
  91301. result.addOptimization(new MergeMeshesOptimization(priority));
  91302. result.addOptimization(new ShadowsOptimization(priority));
  91303. result.addOptimization(new LensFlaresOptimization(priority));
  91304. // Next priority
  91305. priority++;
  91306. result.addOptimization(new PostProcessesOptimization(priority));
  91307. result.addOptimization(new ParticlesOptimization(priority));
  91308. // Next priority
  91309. priority++;
  91310. result.addOptimization(new TextureOptimization(priority, 1024));
  91311. return result;
  91312. };
  91313. /**
  91314. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  91315. * @param targetFrameRate defines the target frame rate (60 by default)
  91316. * @returns a SceneOptimizerOptions object
  91317. */
  91318. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  91319. var result = new SceneOptimizerOptions(targetFrameRate);
  91320. var priority = 0;
  91321. result.addOptimization(new MergeMeshesOptimization(priority));
  91322. result.addOptimization(new ShadowsOptimization(priority));
  91323. result.addOptimization(new LensFlaresOptimization(priority));
  91324. // Next priority
  91325. priority++;
  91326. result.addOptimization(new PostProcessesOptimization(priority));
  91327. result.addOptimization(new ParticlesOptimization(priority));
  91328. // Next priority
  91329. priority++;
  91330. result.addOptimization(new TextureOptimization(priority, 512));
  91331. // Next priority
  91332. priority++;
  91333. result.addOptimization(new RenderTargetsOptimization(priority));
  91334. // Next priority
  91335. priority++;
  91336. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  91337. return result;
  91338. };
  91339. /**
  91340. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  91341. * @param targetFrameRate defines the target frame rate (60 by default)
  91342. * @returns a SceneOptimizerOptions object
  91343. */
  91344. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  91345. var result = new SceneOptimizerOptions(targetFrameRate);
  91346. var priority = 0;
  91347. result.addOptimization(new MergeMeshesOptimization(priority));
  91348. result.addOptimization(new ShadowsOptimization(priority));
  91349. result.addOptimization(new LensFlaresOptimization(priority));
  91350. // Next priority
  91351. priority++;
  91352. result.addOptimization(new PostProcessesOptimization(priority));
  91353. result.addOptimization(new ParticlesOptimization(priority));
  91354. // Next priority
  91355. priority++;
  91356. result.addOptimization(new TextureOptimization(priority, 256));
  91357. // Next priority
  91358. priority++;
  91359. result.addOptimization(new RenderTargetsOptimization(priority));
  91360. // Next priority
  91361. priority++;
  91362. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  91363. return result;
  91364. };
  91365. return SceneOptimizerOptions;
  91366. }());
  91367. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  91368. /**
  91369. * Class used to run optimizations in order to reach a target frame rate
  91370. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91371. */
  91372. var SceneOptimizer = /** @class */ (function () {
  91373. /**
  91374. * Creates a new SceneOptimizer
  91375. * @param scene defines the scene to work on
  91376. * @param options defines the options to use with the SceneOptimizer
  91377. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  91378. * @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)
  91379. */
  91380. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  91381. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  91382. if (improvementMode === void 0) { improvementMode = false; }
  91383. var _this = this;
  91384. this._isRunning = false;
  91385. this._currentPriorityLevel = 0;
  91386. this._targetFrameRate = 60;
  91387. this._trackerDuration = 2000;
  91388. this._currentFrameRate = 0;
  91389. this._improvementMode = false;
  91390. /**
  91391. * Defines an observable called when the optimizer reaches the target frame rate
  91392. */
  91393. this.onSuccessObservable = new BABYLON.Observable();
  91394. /**
  91395. * Defines an observable called when the optimizer enables an optimization
  91396. */
  91397. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  91398. /**
  91399. * Defines an observable called when the optimizer is not able to reach the target frame rate
  91400. */
  91401. this.onFailureObservable = new BABYLON.Observable();
  91402. if (!options) {
  91403. this._options = new SceneOptimizerOptions();
  91404. }
  91405. else {
  91406. this._options = options;
  91407. }
  91408. if (this._options.targetFrameRate) {
  91409. this._targetFrameRate = this._options.targetFrameRate;
  91410. }
  91411. if (this._options.trackerDuration) {
  91412. this._trackerDuration = this._options.trackerDuration;
  91413. }
  91414. if (autoGeneratePriorities) {
  91415. var priority = 0;
  91416. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  91417. var optim = _a[_i];
  91418. optim.priority = priority++;
  91419. }
  91420. }
  91421. this._improvementMode = improvementMode;
  91422. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91423. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  91424. _this._sceneDisposeObserver = null;
  91425. _this.dispose();
  91426. });
  91427. }
  91428. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  91429. /**
  91430. * Gets a boolean indicating if the optimizer is in improvement mode
  91431. */
  91432. get: function () {
  91433. return this._improvementMode;
  91434. },
  91435. enumerable: true,
  91436. configurable: true
  91437. });
  91438. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  91439. /**
  91440. * Gets the current priority level (0 at start)
  91441. */
  91442. get: function () {
  91443. return this._currentPriorityLevel;
  91444. },
  91445. enumerable: true,
  91446. configurable: true
  91447. });
  91448. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  91449. /**
  91450. * Gets the current frame rate checked by the SceneOptimizer
  91451. */
  91452. get: function () {
  91453. return this._currentFrameRate;
  91454. },
  91455. enumerable: true,
  91456. configurable: true
  91457. });
  91458. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  91459. /**
  91460. * Gets or sets the current target frame rate (60 by default)
  91461. */
  91462. get: function () {
  91463. return this._targetFrameRate;
  91464. },
  91465. /**
  91466. * Gets or sets the current target frame rate (60 by default)
  91467. */
  91468. set: function (value) {
  91469. this._targetFrameRate = value;
  91470. },
  91471. enumerable: true,
  91472. configurable: true
  91473. });
  91474. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  91475. /**
  91476. * Gets or sets the current interval between two checks (every 2000ms by default)
  91477. */
  91478. get: function () {
  91479. return this._trackerDuration;
  91480. },
  91481. /**
  91482. * Gets or sets the current interval between two checks (every 2000ms by default)
  91483. */
  91484. set: function (value) {
  91485. this._trackerDuration = value;
  91486. },
  91487. enumerable: true,
  91488. configurable: true
  91489. });
  91490. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  91491. /**
  91492. * Gets the list of active optimizations
  91493. */
  91494. get: function () {
  91495. return this._options.optimizations;
  91496. },
  91497. enumerable: true,
  91498. configurable: true
  91499. });
  91500. /**
  91501. * Stops the current optimizer
  91502. */
  91503. SceneOptimizer.prototype.stop = function () {
  91504. this._isRunning = false;
  91505. };
  91506. /**
  91507. * Reset the optimizer to initial step (current priority level = 0)
  91508. */
  91509. SceneOptimizer.prototype.reset = function () {
  91510. this._currentPriorityLevel = 0;
  91511. };
  91512. /**
  91513. * Start the optimizer. By default it will try to reach a specific framerate
  91514. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  91515. */
  91516. SceneOptimizer.prototype.start = function () {
  91517. var _this = this;
  91518. if (this._isRunning) {
  91519. return;
  91520. }
  91521. this._isRunning = true;
  91522. // Let's wait for the scene to be ready before running our check
  91523. this._scene.executeWhenReady(function () {
  91524. setTimeout(function () {
  91525. _this._checkCurrentState();
  91526. }, _this._trackerDuration);
  91527. });
  91528. };
  91529. SceneOptimizer.prototype._checkCurrentState = function () {
  91530. var _this = this;
  91531. if (!this._isRunning) {
  91532. return;
  91533. }
  91534. var scene = this._scene;
  91535. var options = this._options;
  91536. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91537. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91538. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91539. this._isRunning = false;
  91540. this.onSuccessObservable.notifyObservers(this);
  91541. return;
  91542. }
  91543. // Apply current level of optimizations
  91544. var allDone = true;
  91545. var noOptimizationApplied = true;
  91546. for (var index = 0; index < options.optimizations.length; index++) {
  91547. var optimization = options.optimizations[index];
  91548. if (optimization.priority === this._currentPriorityLevel) {
  91549. noOptimizationApplied = false;
  91550. allDone = allDone && optimization.apply(scene, this);
  91551. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91552. }
  91553. }
  91554. // If no optimization was applied, this is a failure :(
  91555. if (noOptimizationApplied) {
  91556. this._isRunning = false;
  91557. this.onFailureObservable.notifyObservers(this);
  91558. return;
  91559. }
  91560. // If all optimizations were done, move to next level
  91561. if (allDone) {
  91562. this._currentPriorityLevel++;
  91563. }
  91564. // Let's the system running for a specific amount of time before checking FPS
  91565. scene.executeWhenReady(function () {
  91566. setTimeout(function () {
  91567. _this._checkCurrentState();
  91568. }, _this._trackerDuration);
  91569. });
  91570. };
  91571. /**
  91572. * Release all resources
  91573. */
  91574. SceneOptimizer.prototype.dispose = function () {
  91575. this.stop();
  91576. this.onSuccessObservable.clear();
  91577. this.onFailureObservable.clear();
  91578. this.onNewOptimizationAppliedObservable.clear();
  91579. if (this._sceneDisposeObserver) {
  91580. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91581. }
  91582. };
  91583. /**
  91584. * Helper function to create a SceneOptimizer with one single line of code
  91585. * @param scene defines the scene to work on
  91586. * @param options defines the options to use with the SceneOptimizer
  91587. * @param onSuccess defines a callback to call on success
  91588. * @param onFailure defines a callback to call on failure
  91589. * @returns the new SceneOptimizer object
  91590. */
  91591. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91592. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91593. if (onSuccess) {
  91594. optimizer.onSuccessObservable.add(function () {
  91595. onSuccess();
  91596. });
  91597. }
  91598. if (onFailure) {
  91599. optimizer.onFailureObservable.add(function () {
  91600. onFailure();
  91601. });
  91602. }
  91603. optimizer.start();
  91604. return optimizer;
  91605. };
  91606. return SceneOptimizer;
  91607. }());
  91608. BABYLON.SceneOptimizer = SceneOptimizer;
  91609. })(BABYLON || (BABYLON = {}));
  91610. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91611. var BABYLON;
  91612. (function (BABYLON) {
  91613. var OutlineRenderer = /** @class */ (function () {
  91614. function OutlineRenderer(scene) {
  91615. this.zOffset = 1;
  91616. this._scene = scene;
  91617. }
  91618. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91619. var _this = this;
  91620. if (useOverlay === void 0) { useOverlay = false; }
  91621. var scene = this._scene;
  91622. var engine = this._scene.getEngine();
  91623. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91624. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91625. return;
  91626. }
  91627. var mesh = subMesh.getRenderingMesh();
  91628. var material = subMesh.getMaterial();
  91629. if (!material || !scene.activeCamera) {
  91630. return;
  91631. }
  91632. engine.enableEffect(this._effect);
  91633. // Logarithmic depth
  91634. if (material.useLogarithmicDepth) {
  91635. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91636. }
  91637. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91638. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91639. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91640. // Bones
  91641. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91642. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91643. }
  91644. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91645. // Alpha test
  91646. if (material && material.needAlphaTesting()) {
  91647. var alphaTexture = material.getAlphaTestTexture();
  91648. if (alphaTexture) {
  91649. this._effect.setTexture("diffuseSampler", alphaTexture);
  91650. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91651. }
  91652. }
  91653. engine.setZOffset(-this.zOffset);
  91654. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91655. engine.setZOffset(0);
  91656. };
  91657. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91658. var defines = [];
  91659. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91660. var mesh = subMesh.getMesh();
  91661. var material = subMesh.getMaterial();
  91662. if (material) {
  91663. // Alpha test
  91664. if (material.needAlphaTesting()) {
  91665. defines.push("#define ALPHATEST");
  91666. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91667. attribs.push(BABYLON.VertexBuffer.UVKind);
  91668. defines.push("#define UV1");
  91669. }
  91670. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91671. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91672. defines.push("#define UV2");
  91673. }
  91674. }
  91675. //Logarithmic depth
  91676. if (material.useLogarithmicDepth) {
  91677. defines.push("#define LOGARITHMICDEPTH");
  91678. }
  91679. }
  91680. // Bones
  91681. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91682. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91683. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91684. if (mesh.numBoneInfluencers > 4) {
  91685. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91686. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91687. }
  91688. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91689. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91690. }
  91691. else {
  91692. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91693. }
  91694. // Instances
  91695. if (useInstances) {
  91696. defines.push("#define INSTANCES");
  91697. attribs.push("world0");
  91698. attribs.push("world1");
  91699. attribs.push("world2");
  91700. attribs.push("world3");
  91701. }
  91702. // Get correct effect
  91703. var join = defines.join("\n");
  91704. if (this._cachedDefines !== join) {
  91705. this._cachedDefines = join;
  91706. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91707. }
  91708. return this._effect.isReady();
  91709. };
  91710. return OutlineRenderer;
  91711. }());
  91712. BABYLON.OutlineRenderer = OutlineRenderer;
  91713. })(BABYLON || (BABYLON = {}));
  91714. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91715. var BABYLON;
  91716. (function (BABYLON) {
  91717. var FaceAdjacencies = /** @class */ (function () {
  91718. function FaceAdjacencies() {
  91719. this.edges = new Array();
  91720. this.edgesConnectedCount = 0;
  91721. }
  91722. return FaceAdjacencies;
  91723. }());
  91724. var EdgesRenderer = /** @class */ (function () {
  91725. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91726. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91727. if (epsilon === void 0) { epsilon = 0.95; }
  91728. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91729. this.edgesWidthScalerForOrthographic = 1000.0;
  91730. this.edgesWidthScalerForPerspective = 50.0;
  91731. this._linesPositions = new Array();
  91732. this._linesNormals = new Array();
  91733. this._linesIndices = new Array();
  91734. this._buffers = {};
  91735. this._checkVerticesInsteadOfIndices = false;
  91736. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  91737. this.isEnabled = true;
  91738. this._source = source;
  91739. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91740. this._epsilon = epsilon;
  91741. this._prepareRessources();
  91742. this._generateEdgesLines();
  91743. }
  91744. EdgesRenderer.prototype._prepareRessources = function () {
  91745. if (this._lineShader) {
  91746. return;
  91747. }
  91748. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91749. attributes: ["position", "normal"],
  91750. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91751. });
  91752. this._lineShader.disableDepthWrite = true;
  91753. this._lineShader.backFaceCulling = false;
  91754. };
  91755. EdgesRenderer.prototype._rebuild = function () {
  91756. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91757. if (buffer) {
  91758. buffer._rebuild();
  91759. }
  91760. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91761. if (buffer) {
  91762. buffer._rebuild();
  91763. }
  91764. var scene = this._source.getScene();
  91765. var engine = scene.getEngine();
  91766. this._ib = engine.createIndexBuffer(this._linesIndices);
  91767. };
  91768. EdgesRenderer.prototype.dispose = function () {
  91769. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91770. if (buffer) {
  91771. buffer.dispose();
  91772. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91773. }
  91774. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91775. if (buffer) {
  91776. buffer.dispose();
  91777. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91778. }
  91779. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91780. this._lineShader.dispose();
  91781. };
  91782. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91783. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91784. return 0;
  91785. }
  91786. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91787. return 1;
  91788. }
  91789. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91790. return 2;
  91791. }
  91792. return -1;
  91793. };
  91794. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91795. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91796. return 0;
  91797. }
  91798. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91799. return 1;
  91800. }
  91801. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91802. return 2;
  91803. }
  91804. return -1;
  91805. };
  91806. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91807. var needToCreateLine;
  91808. if (edge === undefined) {
  91809. needToCreateLine = true;
  91810. }
  91811. else {
  91812. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91813. needToCreateLine = dotProduct < this._epsilon;
  91814. }
  91815. if (needToCreateLine) {
  91816. var offset = this._linesPositions.length / 3;
  91817. var normal = p0.subtract(p1);
  91818. normal.normalize();
  91819. // Positions
  91820. this._linesPositions.push(p0.x);
  91821. this._linesPositions.push(p0.y);
  91822. this._linesPositions.push(p0.z);
  91823. this._linesPositions.push(p0.x);
  91824. this._linesPositions.push(p0.y);
  91825. this._linesPositions.push(p0.z);
  91826. this._linesPositions.push(p1.x);
  91827. this._linesPositions.push(p1.y);
  91828. this._linesPositions.push(p1.z);
  91829. this._linesPositions.push(p1.x);
  91830. this._linesPositions.push(p1.y);
  91831. this._linesPositions.push(p1.z);
  91832. // Normals
  91833. this._linesNormals.push(p1.x);
  91834. this._linesNormals.push(p1.y);
  91835. this._linesNormals.push(p1.z);
  91836. this._linesNormals.push(-1);
  91837. this._linesNormals.push(p1.x);
  91838. this._linesNormals.push(p1.y);
  91839. this._linesNormals.push(p1.z);
  91840. this._linesNormals.push(1);
  91841. this._linesNormals.push(p0.x);
  91842. this._linesNormals.push(p0.y);
  91843. this._linesNormals.push(p0.z);
  91844. this._linesNormals.push(-1);
  91845. this._linesNormals.push(p0.x);
  91846. this._linesNormals.push(p0.y);
  91847. this._linesNormals.push(p0.z);
  91848. this._linesNormals.push(1);
  91849. // Indices
  91850. this._linesIndices.push(offset);
  91851. this._linesIndices.push(offset + 1);
  91852. this._linesIndices.push(offset + 2);
  91853. this._linesIndices.push(offset);
  91854. this._linesIndices.push(offset + 2);
  91855. this._linesIndices.push(offset + 3);
  91856. }
  91857. };
  91858. EdgesRenderer.prototype._generateEdgesLines = function () {
  91859. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91860. var indices = this._source.getIndices();
  91861. if (!indices || !positions) {
  91862. return;
  91863. }
  91864. // First let's find adjacencies
  91865. var adjacencies = new Array();
  91866. var faceNormals = new Array();
  91867. var index;
  91868. var faceAdjacencies;
  91869. // Prepare faces
  91870. for (index = 0; index < indices.length; index += 3) {
  91871. faceAdjacencies = new FaceAdjacencies();
  91872. var p0Index = indices[index];
  91873. var p1Index = indices[index + 1];
  91874. var p2Index = indices[index + 2];
  91875. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91876. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91877. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91878. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91879. faceNormal.normalize();
  91880. faceNormals.push(faceNormal);
  91881. adjacencies.push(faceAdjacencies);
  91882. }
  91883. // Scan
  91884. for (index = 0; index < adjacencies.length; index++) {
  91885. faceAdjacencies = adjacencies[index];
  91886. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91887. var otherFaceAdjacencies = adjacencies[otherIndex];
  91888. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91889. break;
  91890. }
  91891. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91892. continue;
  91893. }
  91894. var otherP0 = indices[otherIndex * 3];
  91895. var otherP1 = indices[otherIndex * 3 + 1];
  91896. var otherP2 = indices[otherIndex * 3 + 2];
  91897. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91898. var otherEdgeIndex = 0;
  91899. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91900. continue;
  91901. }
  91902. switch (edgeIndex) {
  91903. case 0:
  91904. if (this._checkVerticesInsteadOfIndices) {
  91905. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91906. }
  91907. else {
  91908. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91909. }
  91910. break;
  91911. case 1:
  91912. if (this._checkVerticesInsteadOfIndices) {
  91913. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91914. }
  91915. else {
  91916. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91917. }
  91918. break;
  91919. case 2:
  91920. if (this._checkVerticesInsteadOfIndices) {
  91921. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91922. }
  91923. else {
  91924. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91925. }
  91926. break;
  91927. }
  91928. if (otherEdgeIndex === -1) {
  91929. continue;
  91930. }
  91931. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91932. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91933. faceAdjacencies.edgesConnectedCount++;
  91934. otherFaceAdjacencies.edgesConnectedCount++;
  91935. if (faceAdjacencies.edgesConnectedCount === 3) {
  91936. break;
  91937. }
  91938. }
  91939. }
  91940. }
  91941. // Create lines
  91942. for (index = 0; index < adjacencies.length; index++) {
  91943. // 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
  91944. var current = adjacencies[index];
  91945. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91946. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91947. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91948. }
  91949. // Merge into a single mesh
  91950. var engine = this._source.getScene().getEngine();
  91951. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91952. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91953. this._ib = engine.createIndexBuffer(this._linesIndices);
  91954. this._indicesCount = this._linesIndices.length;
  91955. };
  91956. EdgesRenderer.prototype.render = function () {
  91957. var scene = this._source.getScene();
  91958. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91959. return;
  91960. }
  91961. var engine = scene.getEngine();
  91962. this._lineShader._preBind();
  91963. // VBOs
  91964. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91965. scene.resetCachedMaterial();
  91966. this._lineShader.setColor4("color", this._source.edgesColor);
  91967. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91968. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91969. }
  91970. else {
  91971. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91972. }
  91973. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91974. this._lineShader.bind(this._source.getWorldMatrix());
  91975. // Draw order
  91976. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91977. this._lineShader.unbind();
  91978. engine.setDepthWrite(true);
  91979. };
  91980. return EdgesRenderer;
  91981. }());
  91982. BABYLON.EdgesRenderer = EdgesRenderer;
  91983. })(BABYLON || (BABYLON = {}));
  91984. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91985. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91986. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91987. s = arguments[i];
  91988. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91989. t[p] = s[p];
  91990. }
  91991. return t;
  91992. };
  91993. var BABYLON;
  91994. (function (BABYLON) {
  91995. /**
  91996. * The effect layer Helps adding post process effect blended with the main pass.
  91997. *
  91998. * This can be for instance use to generate glow or higlight effects on the scene.
  91999. *
  92000. * The effect layer class can not be used directly and is intented to inherited from to be
  92001. * customized per effects.
  92002. */
  92003. var EffectLayer = /** @class */ (function () {
  92004. /**
  92005. * Instantiates a new effect Layer and references it in the scene.
  92006. * @param name The name of the layer
  92007. * @param scene The scene to use the layer in
  92008. */
  92009. function EffectLayer(
  92010. /** The Friendly of the effect in the scene */
  92011. name, scene) {
  92012. this._vertexBuffers = {};
  92013. this._maxSize = 0;
  92014. this._mainTextureDesiredSize = { width: 0, height: 0 };
  92015. this._shouldRender = true;
  92016. this._postProcesses = [];
  92017. this._textures = [];
  92018. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  92019. /**
  92020. * The clear color of the texture used to generate the glow map.
  92021. */
  92022. this.neutralColor = new BABYLON.Color4();
  92023. /**
  92024. * Specifies wether the highlight layer is enabled or not.
  92025. */
  92026. this.isEnabled = true;
  92027. /**
  92028. * An event triggered when the effect layer has been disposed.
  92029. */
  92030. this.onDisposeObservable = new BABYLON.Observable();
  92031. /**
  92032. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  92033. */
  92034. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  92035. /**
  92036. * An event triggered when the generated texture is being merged in the scene.
  92037. */
  92038. this.onBeforeComposeObservable = new BABYLON.Observable();
  92039. /**
  92040. * An event triggered when the generated texture has been merged in the scene.
  92041. */
  92042. this.onAfterComposeObservable = new BABYLON.Observable();
  92043. /**
  92044. * An event triggered when the efffect layer changes its size.
  92045. */
  92046. this.onSizeChangedObservable = new BABYLON.Observable();
  92047. this.name = name;
  92048. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92049. this._engine = scene.getEngine();
  92050. this._maxSize = this._engine.getCaps().maxTextureSize;
  92051. this._scene.effectLayers.push(this);
  92052. // Generate Buffers
  92053. this._generateIndexBuffer();
  92054. this._genrateVertexBuffer();
  92055. }
  92056. Object.defineProperty(EffectLayer.prototype, "camera", {
  92057. /**
  92058. * Gets the camera attached to the layer.
  92059. */
  92060. get: function () {
  92061. return this._effectLayerOptions.camera;
  92062. },
  92063. enumerable: true,
  92064. configurable: true
  92065. });
  92066. /**
  92067. * Initializes the effect layer with the required options.
  92068. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  92069. */
  92070. EffectLayer.prototype._init = function (options) {
  92071. // Adapt options
  92072. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92073. this._setMainTextureSize();
  92074. this._createMainTexture();
  92075. this._createTextureAndPostProcesses();
  92076. this._mergeEffect = this._createMergeEffect();
  92077. };
  92078. /**
  92079. * Generates the index buffer of the full screen quad blending to the main canvas.
  92080. */
  92081. EffectLayer.prototype._generateIndexBuffer = function () {
  92082. // Indices
  92083. var indices = [];
  92084. indices.push(0);
  92085. indices.push(1);
  92086. indices.push(2);
  92087. indices.push(0);
  92088. indices.push(2);
  92089. indices.push(3);
  92090. this._indexBuffer = this._engine.createIndexBuffer(indices);
  92091. };
  92092. /**
  92093. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  92094. */
  92095. EffectLayer.prototype._genrateVertexBuffer = function () {
  92096. // VBO
  92097. var vertices = [];
  92098. vertices.push(1, 1);
  92099. vertices.push(-1, 1);
  92100. vertices.push(-1, -1);
  92101. vertices.push(1, -1);
  92102. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92103. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92104. };
  92105. /**
  92106. * Sets the main texture desired size which is the closest power of two
  92107. * of the engine canvas size.
  92108. */
  92109. EffectLayer.prototype._setMainTextureSize = function () {
  92110. if (this._effectLayerOptions.mainTextureFixedSize) {
  92111. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  92112. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  92113. }
  92114. else {
  92115. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  92116. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  92117. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  92118. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  92119. }
  92120. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  92121. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  92122. };
  92123. /**
  92124. * Creates the main texture for the effect layer.
  92125. */
  92126. EffectLayer.prototype._createMainTexture = function () {
  92127. var _this = this;
  92128. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  92129. width: this._mainTextureDesiredSize.width,
  92130. height: this._mainTextureDesiredSize.height
  92131. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92132. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  92133. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92134. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92135. this._mainTexture.anisotropicFilteringLevel = 1;
  92136. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92137. this._mainTexture.renderParticles = false;
  92138. this._mainTexture.renderList = null;
  92139. this._mainTexture.ignoreCameraViewport = true;
  92140. // Custom render function
  92141. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  92142. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  92143. var index;
  92144. var engine = _this._scene.getEngine();
  92145. if (depthOnlySubMeshes.length) {
  92146. engine.setColorWrite(false);
  92147. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  92148. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  92149. }
  92150. engine.setColorWrite(true);
  92151. }
  92152. for (index = 0; index < opaqueSubMeshes.length; index++) {
  92153. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  92154. }
  92155. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  92156. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  92157. }
  92158. for (index = 0; index < transparentSubMeshes.length; index++) {
  92159. _this._renderSubMesh(transparentSubMeshes.data[index]);
  92160. }
  92161. };
  92162. this._mainTexture.onClearObservable.add(function (engine) {
  92163. engine.clear(_this.neutralColor, true, true, true);
  92164. });
  92165. };
  92166. /**
  92167. * Checks for the readiness of the element composing the layer.
  92168. * @param subMesh the mesh to check for
  92169. * @param useInstances specify wether or not to use instances to render the mesh
  92170. * @param emissiveTexture the associated emissive texture used to generate the glow
  92171. * @return true if ready otherwise, false
  92172. */
  92173. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  92174. var material = subMesh.getMaterial();
  92175. if (!material) {
  92176. return false;
  92177. }
  92178. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  92179. return false;
  92180. }
  92181. var defines = [];
  92182. var attribs = [BABYLON.VertexBuffer.PositionKind];
  92183. var mesh = subMesh.getMesh();
  92184. var uv1 = false;
  92185. var uv2 = false;
  92186. // Alpha test
  92187. if (material && material.needAlphaTesting()) {
  92188. var alphaTexture = material.getAlphaTestTexture();
  92189. if (alphaTexture) {
  92190. defines.push("#define ALPHATEST");
  92191. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92192. alphaTexture.coordinatesIndex === 1) {
  92193. defines.push("#define DIFFUSEUV2");
  92194. uv2 = true;
  92195. }
  92196. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92197. defines.push("#define DIFFUSEUV1");
  92198. uv1 = true;
  92199. }
  92200. }
  92201. }
  92202. // Emissive
  92203. if (emissiveTexture) {
  92204. defines.push("#define EMISSIVE");
  92205. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92206. emissiveTexture.coordinatesIndex === 1) {
  92207. defines.push("#define EMISSIVEUV2");
  92208. uv2 = true;
  92209. }
  92210. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92211. defines.push("#define EMISSIVEUV1");
  92212. uv1 = true;
  92213. }
  92214. }
  92215. if (uv1) {
  92216. attribs.push(BABYLON.VertexBuffer.UVKind);
  92217. defines.push("#define UV1");
  92218. }
  92219. if (uv2) {
  92220. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92221. defines.push("#define UV2");
  92222. }
  92223. // Bones
  92224. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  92225. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  92226. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  92227. if (mesh.numBoneInfluencers > 4) {
  92228. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  92229. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  92230. }
  92231. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  92232. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  92233. }
  92234. else {
  92235. defines.push("#define NUM_BONE_INFLUENCERS 0");
  92236. }
  92237. // Morph targets
  92238. var manager = mesh.morphTargetManager;
  92239. var morphInfluencers = 0;
  92240. if (manager) {
  92241. if (manager.numInfluencers > 0) {
  92242. defines.push("#define MORPHTARGETS");
  92243. morphInfluencers = manager.numInfluencers;
  92244. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  92245. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  92246. }
  92247. }
  92248. // Instances
  92249. if (useInstances) {
  92250. defines.push("#define INSTANCES");
  92251. attribs.push("world0");
  92252. attribs.push("world1");
  92253. attribs.push("world2");
  92254. attribs.push("world3");
  92255. }
  92256. // Get correct effect
  92257. var join = defines.join("\n");
  92258. if (this._cachedDefines !== join) {
  92259. this._cachedDefines = join;
  92260. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  92261. }
  92262. return this._effectLayerMapGenerationEffect.isReady();
  92263. };
  92264. /**
  92265. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  92266. */
  92267. EffectLayer.prototype.render = function () {
  92268. var currentEffect = this._mergeEffect;
  92269. // Check
  92270. if (!currentEffect.isReady())
  92271. return;
  92272. for (var i = 0; i < this._postProcesses.length; i++) {
  92273. if (!this._postProcesses[i].isReady()) {
  92274. return;
  92275. }
  92276. }
  92277. var engine = this._scene.getEngine();
  92278. this.onBeforeComposeObservable.notifyObservers(this);
  92279. // Render
  92280. engine.enableEffect(currentEffect);
  92281. engine.setState(false);
  92282. // VBOs
  92283. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  92284. // Cache
  92285. var previousAlphaMode = engine.getAlphaMode();
  92286. // Go Blend.
  92287. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  92288. // Blends the map on the main canvas.
  92289. this._internalRender(currentEffect);
  92290. // Restore Alpha
  92291. engine.setAlphaMode(previousAlphaMode);
  92292. this.onAfterComposeObservable.notifyObservers(this);
  92293. // Handle size changes.
  92294. var size = this._mainTexture.getSize();
  92295. this._setMainTextureSize();
  92296. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  92297. // Recreate RTT and post processes on size change.
  92298. this.onSizeChangedObservable.notifyObservers(this);
  92299. this._disposeTextureAndPostProcesses();
  92300. this._createMainTexture();
  92301. this._createTextureAndPostProcesses();
  92302. }
  92303. };
  92304. /**
  92305. * Determine if a given mesh will be used in the current effect.
  92306. * @param mesh mesh to test
  92307. * @returns true if the mesh will be used
  92308. */
  92309. EffectLayer.prototype.hasMesh = function (mesh) {
  92310. return true;
  92311. };
  92312. /**
  92313. * Returns true if the layer contains information to display, otherwise false.
  92314. * @returns true if the glow layer should be rendered
  92315. */
  92316. EffectLayer.prototype.shouldRender = function () {
  92317. return this.isEnabled && this._shouldRender;
  92318. };
  92319. /**
  92320. * Returns true if the mesh should render, otherwise false.
  92321. * @param mesh The mesh to render
  92322. * @returns true if it should render otherwise false
  92323. */
  92324. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  92325. return true;
  92326. };
  92327. /**
  92328. * Returns true if the mesh should render, otherwise false.
  92329. * @param mesh The mesh to render
  92330. * @returns true if it should render otherwise false
  92331. */
  92332. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  92333. return true;
  92334. };
  92335. /**
  92336. * Renders the submesh passed in parameter to the generation map.
  92337. */
  92338. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  92339. var _this = this;
  92340. if (!this.shouldRender()) {
  92341. return;
  92342. }
  92343. var material = subMesh.getMaterial();
  92344. var mesh = subMesh.getRenderingMesh();
  92345. var scene = this._scene;
  92346. var engine = scene.getEngine();
  92347. if (!material) {
  92348. return;
  92349. }
  92350. // Do not block in blend mode.
  92351. if (material.needAlphaBlendingForMesh(mesh)) {
  92352. return;
  92353. }
  92354. // Culling
  92355. engine.setState(material.backFaceCulling);
  92356. // Managing instances
  92357. var batch = mesh._getInstancesRenderList(subMesh._id);
  92358. if (batch.mustReturn) {
  92359. return;
  92360. }
  92361. // Early Exit per mesh
  92362. if (!this._shouldRenderMesh(mesh)) {
  92363. return;
  92364. }
  92365. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  92366. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  92367. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  92368. engine.enableEffect(this._effectLayerMapGenerationEffect);
  92369. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  92370. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  92371. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  92372. // Alpha test
  92373. if (material && material.needAlphaTesting()) {
  92374. var alphaTexture = material.getAlphaTestTexture();
  92375. if (alphaTexture) {
  92376. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  92377. var textureMatrix = alphaTexture.getTextureMatrix();
  92378. if (textureMatrix) {
  92379. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  92380. }
  92381. }
  92382. }
  92383. // Glow emissive only
  92384. if (this._emissiveTextureAndColor.texture) {
  92385. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  92386. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  92387. }
  92388. // Bones
  92389. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92390. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92391. }
  92392. // Morph targets
  92393. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  92394. // Draw
  92395. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  92396. }
  92397. else {
  92398. // Need to reset refresh rate of the shadowMap
  92399. this._mainTexture.resetRefreshCounter();
  92400. }
  92401. };
  92402. /**
  92403. * Rebuild the required buffers.
  92404. * @hidden Internal use only.
  92405. */
  92406. EffectLayer.prototype._rebuild = function () {
  92407. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92408. if (vb) {
  92409. vb._rebuild();
  92410. }
  92411. this._generateIndexBuffer();
  92412. };
  92413. /**
  92414. * Dispose only the render target textures and post process.
  92415. */
  92416. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  92417. this._mainTexture.dispose();
  92418. for (var i = 0; i < this._postProcesses.length; i++) {
  92419. if (this._postProcesses[i]) {
  92420. this._postProcesses[i].dispose();
  92421. }
  92422. }
  92423. this._postProcesses = [];
  92424. for (var i = 0; i < this._textures.length; i++) {
  92425. if (this._textures[i]) {
  92426. this._textures[i].dispose();
  92427. }
  92428. }
  92429. this._textures = [];
  92430. };
  92431. /**
  92432. * Dispose the highlight layer and free resources.
  92433. */
  92434. EffectLayer.prototype.dispose = function () {
  92435. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92436. if (vertexBuffer) {
  92437. vertexBuffer.dispose();
  92438. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92439. }
  92440. if (this._indexBuffer) {
  92441. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92442. this._indexBuffer = null;
  92443. }
  92444. // Clean textures and post processes
  92445. this._disposeTextureAndPostProcesses();
  92446. // Remove from scene
  92447. var index = this._scene.effectLayers.indexOf(this, 0);
  92448. if (index > -1) {
  92449. this._scene.effectLayers.splice(index, 1);
  92450. }
  92451. // Callback
  92452. this.onDisposeObservable.notifyObservers(this);
  92453. this.onDisposeObservable.clear();
  92454. this.onBeforeRenderMainTextureObservable.clear();
  92455. this.onBeforeComposeObservable.clear();
  92456. this.onAfterComposeObservable.clear();
  92457. this.onSizeChangedObservable.clear();
  92458. };
  92459. /**
  92460. * Gets the class name of the effect layer
  92461. * @returns the string with the class name of the effect layer
  92462. */
  92463. EffectLayer.prototype.getClassName = function () {
  92464. return "EffectLayer";
  92465. };
  92466. /**
  92467. * Creates an effect layer from parsed effect layer data
  92468. * @param parsedEffectLayer defines effect layer data
  92469. * @param scene defines the current scene
  92470. * @param rootUrl defines the root URL containing the effect layer information
  92471. * @returns a parsed effect Layer
  92472. */
  92473. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  92474. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  92475. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  92476. };
  92477. __decorate([
  92478. BABYLON.serialize()
  92479. ], EffectLayer.prototype, "name", void 0);
  92480. __decorate([
  92481. BABYLON.serializeAsColor4()
  92482. ], EffectLayer.prototype, "neutralColor", void 0);
  92483. __decorate([
  92484. BABYLON.serialize()
  92485. ], EffectLayer.prototype, "isEnabled", void 0);
  92486. __decorate([
  92487. BABYLON.serializeAsCameraReference()
  92488. ], EffectLayer.prototype, "camera", null);
  92489. return EffectLayer;
  92490. }());
  92491. BABYLON.EffectLayer = EffectLayer;
  92492. })(BABYLON || (BABYLON = {}));
  92493. //# sourceMappingURL=babylon.effectLayer.js.map
  92494. var BABYLON;
  92495. (function (BABYLON) {
  92496. /**
  92497. * Special Glow Blur post process only blurring the alpha channel
  92498. * It enforces keeping the most luminous color in the color channel.
  92499. */
  92500. var GlowBlurPostProcess = /** @class */ (function (_super) {
  92501. __extends(GlowBlurPostProcess, _super);
  92502. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  92503. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  92504. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  92505. _this.direction = direction;
  92506. _this.kernel = kernel;
  92507. _this.onApplyObservable.add(function (effect) {
  92508. effect.setFloat2("screenSize", _this.width, _this.height);
  92509. effect.setVector2("direction", _this.direction);
  92510. effect.setFloat("blurWidth", _this.kernel);
  92511. });
  92512. return _this;
  92513. }
  92514. return GlowBlurPostProcess;
  92515. }(BABYLON.PostProcess));
  92516. /**
  92517. * The highlight layer Helps adding a glow effect around a mesh.
  92518. *
  92519. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92520. * glowy meshes to your scene.
  92521. *
  92522. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  92523. */
  92524. var HighlightLayer = /** @class */ (function (_super) {
  92525. __extends(HighlightLayer, _super);
  92526. /**
  92527. * Instantiates a new highlight Layer and references it to the scene..
  92528. * @param name The name of the layer
  92529. * @param scene The scene to use the layer in
  92530. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  92531. */
  92532. function HighlightLayer(name, scene, options) {
  92533. var _this = _super.call(this, name, scene) || this;
  92534. _this.name = name;
  92535. /**
  92536. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92537. */
  92538. _this.innerGlow = true;
  92539. /**
  92540. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92541. */
  92542. _this.outerGlow = true;
  92543. /**
  92544. * An event triggered when the highlight layer is being blurred.
  92545. */
  92546. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92547. /**
  92548. * An event triggered when the highlight layer has been blurred.
  92549. */
  92550. _this.onAfterBlurObservable = new BABYLON.Observable();
  92551. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92552. _this._meshes = {};
  92553. _this._excludedMeshes = {};
  92554. _this.neutralColor = HighlightLayer.NeutralColor;
  92555. // Warn on stencil
  92556. if (!_this._engine.isStencilEnable) {
  92557. 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 }");
  92558. }
  92559. // Adapt options
  92560. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92561. // Initialize the layer
  92562. _this._init({
  92563. alphaBlendingMode: _this._options.alphaBlendingMode,
  92564. camera: _this._options.camera,
  92565. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92566. mainTextureRatio: _this._options.mainTextureRatio
  92567. });
  92568. // Do not render as long as no meshes have been added
  92569. _this._shouldRender = false;
  92570. return _this;
  92571. }
  92572. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92573. /**
  92574. * Gets the horizontal size of the blur.
  92575. */
  92576. get: function () {
  92577. return this._horizontalBlurPostprocess.kernel;
  92578. },
  92579. /**
  92580. * Specifies the horizontal size of the blur.
  92581. */
  92582. set: function (value) {
  92583. this._horizontalBlurPostprocess.kernel = value;
  92584. },
  92585. enumerable: true,
  92586. configurable: true
  92587. });
  92588. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92589. /**
  92590. * Gets the vertical size of the blur.
  92591. */
  92592. get: function () {
  92593. return this._verticalBlurPostprocess.kernel;
  92594. },
  92595. /**
  92596. * Specifies the vertical size of the blur.
  92597. */
  92598. set: function (value) {
  92599. this._verticalBlurPostprocess.kernel = value;
  92600. },
  92601. enumerable: true,
  92602. configurable: true
  92603. });
  92604. /**
  92605. * Get the effect name of the layer.
  92606. * @return The effect name
  92607. */
  92608. HighlightLayer.prototype.getEffectName = function () {
  92609. return HighlightLayer.EffectName;
  92610. };
  92611. /**
  92612. * Create the merge effect. This is the shader use to blit the information back
  92613. * to the main canvas at the end of the scene rendering.
  92614. */
  92615. HighlightLayer.prototype._createMergeEffect = function () {
  92616. // Effect
  92617. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92618. };
  92619. /**
  92620. * Creates the render target textures and post processes used in the highlight layer.
  92621. */
  92622. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92623. var _this = this;
  92624. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92625. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92626. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92627. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92628. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92629. width: blurTextureWidth,
  92630. height: blurTextureHeight
  92631. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92632. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92633. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92634. this._blurTexture.anisotropicFilteringLevel = 16;
  92635. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92636. this._blurTexture.renderParticles = false;
  92637. this._blurTexture.ignoreCameraViewport = true;
  92638. this._textures = [this._blurTexture];
  92639. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92640. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92641. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92642. effect.setTexture("textureSampler", _this._mainTexture);
  92643. });
  92644. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92645. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92646. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92647. });
  92648. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92649. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92650. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92651. });
  92652. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92653. }
  92654. else {
  92655. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92656. width: blurTextureWidth,
  92657. height: blurTextureHeight
  92658. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92659. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92660. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92661. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92662. effect.setTexture("textureSampler", _this._mainTexture);
  92663. });
  92664. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92665. width: blurTextureWidth,
  92666. height: blurTextureHeight
  92667. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92668. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92669. }
  92670. this._mainTexture.onAfterUnbindObservable.add(function () {
  92671. _this.onBeforeBlurObservable.notifyObservers(_this);
  92672. var internalTexture = _this._blurTexture.getInternalTexture();
  92673. if (internalTexture) {
  92674. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92675. }
  92676. _this.onAfterBlurObservable.notifyObservers(_this);
  92677. });
  92678. // Prevent autoClear.
  92679. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92680. };
  92681. /**
  92682. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92683. */
  92684. HighlightLayer.prototype.needStencil = function () {
  92685. return true;
  92686. };
  92687. /**
  92688. * Checks for the readiness of the element composing the layer.
  92689. * @param subMesh the mesh to check for
  92690. * @param useInstances specify wether or not to use instances to render the mesh
  92691. * @param emissiveTexture the associated emissive texture used to generate the glow
  92692. * @return true if ready otherwise, false
  92693. */
  92694. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92695. var material = subMesh.getMaterial();
  92696. var mesh = subMesh.getRenderingMesh();
  92697. if (!material || !mesh || !this._meshes) {
  92698. return false;
  92699. }
  92700. var emissiveTexture = null;
  92701. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92702. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92703. emissiveTexture = material.emissiveTexture;
  92704. }
  92705. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92706. };
  92707. /**
  92708. * Implementation specific of rendering the generating effect on the main canvas.
  92709. * @param effect The effect used to render through
  92710. */
  92711. HighlightLayer.prototype._internalRender = function (effect) {
  92712. // Texture
  92713. effect.setTexture("textureSampler", this._blurTexture);
  92714. // Cache
  92715. var engine = this._engine;
  92716. var previousStencilBuffer = engine.getStencilBuffer();
  92717. var previousStencilFunction = engine.getStencilFunction();
  92718. var previousStencilMask = engine.getStencilMask();
  92719. var previousStencilOperationPass = engine.getStencilOperationPass();
  92720. var previousStencilOperationFail = engine.getStencilOperationFail();
  92721. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92722. var previousStencilReference = engine.getStencilFunctionReference();
  92723. // Stencil operations
  92724. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92725. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92726. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92727. // Draw order
  92728. engine.setStencilMask(0x00);
  92729. engine.setStencilBuffer(true);
  92730. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92731. // 2 passes inner outer
  92732. if (this.outerGlow) {
  92733. effect.setFloat("offset", 0);
  92734. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92735. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92736. }
  92737. if (this.innerGlow) {
  92738. effect.setFloat("offset", 1);
  92739. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92740. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92741. }
  92742. // Restore Cache
  92743. engine.setStencilFunction(previousStencilFunction);
  92744. engine.setStencilMask(previousStencilMask);
  92745. engine.setStencilBuffer(previousStencilBuffer);
  92746. engine.setStencilOperationPass(previousStencilOperationPass);
  92747. engine.setStencilOperationFail(previousStencilOperationFail);
  92748. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92749. engine.setStencilFunctionReference(previousStencilReference);
  92750. };
  92751. /**
  92752. * Returns true if the layer contains information to display, otherwise false.
  92753. */
  92754. HighlightLayer.prototype.shouldRender = function () {
  92755. if (_super.prototype.shouldRender.call(this)) {
  92756. return this._meshes ? true : false;
  92757. }
  92758. return false;
  92759. };
  92760. /**
  92761. * Returns true if the mesh should render, otherwise false.
  92762. * @param mesh The mesh to render
  92763. * @returns true if it should render otherwise false
  92764. */
  92765. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92766. // Excluded Mesh
  92767. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92768. return false;
  92769. }
  92770. ;
  92771. return true;
  92772. };
  92773. /**
  92774. * Sets the required values for both the emissive texture and and the main color.
  92775. */
  92776. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92777. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92778. if (highlightLayerMesh) {
  92779. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92780. }
  92781. else {
  92782. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92783. }
  92784. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92785. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92786. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92787. }
  92788. else {
  92789. this._emissiveTextureAndColor.texture = null;
  92790. }
  92791. };
  92792. /**
  92793. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92794. * @param mesh The mesh to exclude from the highlight layer
  92795. */
  92796. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92797. if (!this._excludedMeshes) {
  92798. return;
  92799. }
  92800. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92801. if (!meshExcluded) {
  92802. this._excludedMeshes[mesh.uniqueId] = {
  92803. mesh: mesh,
  92804. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92805. mesh.getEngine().setStencilBuffer(false);
  92806. }),
  92807. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92808. mesh.getEngine().setStencilBuffer(true);
  92809. }),
  92810. };
  92811. }
  92812. };
  92813. /**
  92814. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92815. * @param mesh The mesh to highlight
  92816. */
  92817. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92818. if (!this._excludedMeshes) {
  92819. return;
  92820. }
  92821. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92822. if (meshExcluded) {
  92823. if (meshExcluded.beforeRender) {
  92824. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92825. }
  92826. if (meshExcluded.afterRender) {
  92827. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92828. }
  92829. }
  92830. this._excludedMeshes[mesh.uniqueId] = null;
  92831. };
  92832. /**
  92833. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92834. * @param mesh mesh to test
  92835. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92836. */
  92837. HighlightLayer.prototype.hasMesh = function (mesh) {
  92838. if (!this._meshes) {
  92839. return false;
  92840. }
  92841. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92842. };
  92843. /**
  92844. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92845. * @param mesh The mesh to highlight
  92846. * @param color The color of the highlight
  92847. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92848. */
  92849. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92850. var _this = this;
  92851. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92852. if (!this._meshes) {
  92853. return;
  92854. }
  92855. var meshHighlight = this._meshes[mesh.uniqueId];
  92856. if (meshHighlight) {
  92857. meshHighlight.color = color;
  92858. }
  92859. else {
  92860. this._meshes[mesh.uniqueId] = {
  92861. mesh: mesh,
  92862. color: color,
  92863. // Lambda required for capture due to Observable this context
  92864. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92865. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92866. _this._defaultStencilReference(mesh);
  92867. }
  92868. else {
  92869. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92870. }
  92871. }),
  92872. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92873. glowEmissiveOnly: glowEmissiveOnly
  92874. };
  92875. }
  92876. this._shouldRender = true;
  92877. };
  92878. /**
  92879. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92880. * @param mesh The mesh to highlight
  92881. */
  92882. HighlightLayer.prototype.removeMesh = function (mesh) {
  92883. if (!this._meshes) {
  92884. return;
  92885. }
  92886. var meshHighlight = this._meshes[mesh.uniqueId];
  92887. if (meshHighlight) {
  92888. if (meshHighlight.observerHighlight) {
  92889. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92890. }
  92891. if (meshHighlight.observerDefault) {
  92892. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92893. }
  92894. delete this._meshes[mesh.uniqueId];
  92895. }
  92896. this._shouldRender = false;
  92897. for (var meshHighlightToCheck in this._meshes) {
  92898. if (this._meshes[meshHighlightToCheck]) {
  92899. this._shouldRender = true;
  92900. break;
  92901. }
  92902. }
  92903. };
  92904. /**
  92905. * Force the stencil to the normal expected value for none glowing parts
  92906. */
  92907. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92908. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92909. };
  92910. /**
  92911. * Free any resources and references associated to a mesh.
  92912. * Internal use
  92913. * @param mesh The mesh to free.
  92914. */
  92915. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92916. this.removeMesh(mesh);
  92917. this.removeExcludedMesh(mesh);
  92918. };
  92919. /**
  92920. * Dispose the highlight layer and free resources.
  92921. */
  92922. HighlightLayer.prototype.dispose = function () {
  92923. if (this._meshes) {
  92924. // Clean mesh references
  92925. for (var id in this._meshes) {
  92926. var meshHighlight = this._meshes[id];
  92927. if (meshHighlight && meshHighlight.mesh) {
  92928. if (meshHighlight.observerHighlight) {
  92929. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92930. }
  92931. if (meshHighlight.observerDefault) {
  92932. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92933. }
  92934. }
  92935. }
  92936. this._meshes = null;
  92937. }
  92938. if (this._excludedMeshes) {
  92939. for (var id in this._excludedMeshes) {
  92940. var meshHighlight = this._excludedMeshes[id];
  92941. if (meshHighlight) {
  92942. if (meshHighlight.beforeRender) {
  92943. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92944. }
  92945. if (meshHighlight.afterRender) {
  92946. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92947. }
  92948. }
  92949. }
  92950. this._excludedMeshes = null;
  92951. }
  92952. _super.prototype.dispose.call(this);
  92953. };
  92954. /**
  92955. * Gets the class name of the effect layer
  92956. * @returns the string with the class name of the effect layer
  92957. */
  92958. HighlightLayer.prototype.getClassName = function () {
  92959. return "HighlightLayer";
  92960. };
  92961. /**
  92962. * Serializes this Highlight layer
  92963. * @returns a serialized Highlight layer object
  92964. */
  92965. HighlightLayer.prototype.serialize = function () {
  92966. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92967. serializationObject.customType = "BABYLON.HighlightLayer";
  92968. // Highlighted meshes
  92969. serializationObject.meshes = [];
  92970. if (this._meshes) {
  92971. for (var m in this._meshes) {
  92972. var mesh = this._meshes[m];
  92973. if (mesh) {
  92974. serializationObject.meshes.push({
  92975. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92976. color: mesh.color.asArray(),
  92977. meshId: mesh.mesh.id
  92978. });
  92979. }
  92980. }
  92981. }
  92982. // Excluded meshes
  92983. serializationObject.excludedMeshes = [];
  92984. if (this._excludedMeshes) {
  92985. for (var e in this._excludedMeshes) {
  92986. var excludedMesh = this._excludedMeshes[e];
  92987. if (excludedMesh) {
  92988. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92989. }
  92990. }
  92991. }
  92992. return serializationObject;
  92993. };
  92994. /**
  92995. * Creates a Highlight layer from parsed Highlight layer data
  92996. * @param parsedHightlightLayer defines the Highlight layer data
  92997. * @param scene defines the current scene
  92998. * @param rootUrl defines the root URL containing the Highlight layer information
  92999. * @returns a parsed Highlight layer
  93000. */
  93001. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  93002. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  93003. var index;
  93004. // Excluded meshes
  93005. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  93006. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  93007. if (mesh) {
  93008. hl.addExcludedMesh(mesh);
  93009. }
  93010. }
  93011. // Included meshes
  93012. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  93013. var highlightedMesh = parsedHightlightLayer.meshes[index];
  93014. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  93015. if (mesh) {
  93016. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  93017. }
  93018. }
  93019. return hl;
  93020. };
  93021. /**
  93022. * Effect Name of the highlight layer.
  93023. */
  93024. HighlightLayer.EffectName = "HighlightLayer";
  93025. /**
  93026. * The neutral color used during the preparation of the glow effect.
  93027. * This is black by default as the blend operation is a blend operation.
  93028. */
  93029. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  93030. /**
  93031. * Stencil value used for glowing meshes.
  93032. */
  93033. HighlightLayer.GlowingMeshStencilReference = 0x02;
  93034. /**
  93035. * Stencil value used for the other meshes in the scene.
  93036. */
  93037. HighlightLayer.NormalMeshStencilReference = 0x01;
  93038. __decorate([
  93039. BABYLON.serialize()
  93040. ], HighlightLayer.prototype, "innerGlow", void 0);
  93041. __decorate([
  93042. BABYLON.serialize()
  93043. ], HighlightLayer.prototype, "outerGlow", void 0);
  93044. __decorate([
  93045. BABYLON.serialize()
  93046. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  93047. __decorate([
  93048. BABYLON.serialize()
  93049. ], HighlightLayer.prototype, "blurVerticalSize", null);
  93050. __decorate([
  93051. BABYLON.serialize("options")
  93052. ], HighlightLayer.prototype, "_options", void 0);
  93053. return HighlightLayer;
  93054. }(BABYLON.EffectLayer));
  93055. BABYLON.HighlightLayer = HighlightLayer;
  93056. })(BABYLON || (BABYLON = {}));
  93057. //# sourceMappingURL=babylon.highlightLayer.js.map
  93058. var BABYLON;
  93059. (function (BABYLON) {
  93060. /**
  93061. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  93062. *
  93063. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93064. * glowy meshes to your scene.
  93065. *
  93066. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  93067. */
  93068. var GlowLayer = /** @class */ (function (_super) {
  93069. __extends(GlowLayer, _super);
  93070. /**
  93071. * Instantiates a new glow Layer and references it to the scene.
  93072. * @param name The name of the layer
  93073. * @param scene The scene to use the layer in
  93074. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  93075. */
  93076. function GlowLayer(name, scene, options) {
  93077. var _this = _super.call(this, name, scene) || this;
  93078. _this._intensity = 1.0;
  93079. _this._includedOnlyMeshes = [];
  93080. _this._excludedMeshes = [];
  93081. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  93082. // Adapt options
  93083. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  93084. // Initialize the layer
  93085. _this._init({
  93086. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  93087. camera: _this._options.camera,
  93088. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  93089. mainTextureRatio: _this._options.mainTextureRatio
  93090. });
  93091. return _this;
  93092. }
  93093. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  93094. /**
  93095. * Gets the kernel size of the blur.
  93096. */
  93097. get: function () {
  93098. return this._horizontalBlurPostprocess1.kernel;
  93099. },
  93100. /**
  93101. * Sets the kernel size of the blur.
  93102. */
  93103. set: function (value) {
  93104. this._horizontalBlurPostprocess1.kernel = value;
  93105. this._verticalBlurPostprocess1.kernel = value;
  93106. this._horizontalBlurPostprocess2.kernel = value;
  93107. this._verticalBlurPostprocess2.kernel = value;
  93108. },
  93109. enumerable: true,
  93110. configurable: true
  93111. });
  93112. Object.defineProperty(GlowLayer.prototype, "intensity", {
  93113. /**
  93114. * Gets the glow intensity.
  93115. */
  93116. get: function () {
  93117. return this._intensity;
  93118. },
  93119. /**
  93120. * Sets the glow intensity.
  93121. */
  93122. set: function (value) {
  93123. this._intensity = value;
  93124. },
  93125. enumerable: true,
  93126. configurable: true
  93127. });
  93128. /**
  93129. * Get the effect name of the layer.
  93130. * @return The effect name
  93131. */
  93132. GlowLayer.prototype.getEffectName = function () {
  93133. return GlowLayer.EffectName;
  93134. };
  93135. /**
  93136. * Create the merge effect. This is the shader use to blit the information back
  93137. * to the main canvas at the end of the scene rendering.
  93138. */
  93139. GlowLayer.prototype._createMergeEffect = function () {
  93140. // Effect
  93141. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  93142. };
  93143. /**
  93144. * Creates the render target textures and post processes used in the glow layer.
  93145. */
  93146. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  93147. var _this = this;
  93148. var blurTextureWidth = this._mainTextureDesiredSize.width;
  93149. var blurTextureHeight = this._mainTextureDesiredSize.height;
  93150. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  93151. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  93152. var textureType = 0;
  93153. if (this._engine.getCaps().textureHalfFloatRender) {
  93154. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93155. }
  93156. else {
  93157. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93158. }
  93159. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  93160. width: blurTextureWidth,
  93161. height: blurTextureHeight
  93162. }, this._scene, false, true, textureType);
  93163. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93164. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93165. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93166. this._blurTexture1.renderParticles = false;
  93167. this._blurTexture1.ignoreCameraViewport = true;
  93168. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  93169. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  93170. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  93171. width: blurTextureWidth2,
  93172. height: blurTextureHeight2
  93173. }, this._scene, false, true, textureType);
  93174. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93175. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93176. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93177. this._blurTexture2.renderParticles = false;
  93178. this._blurTexture2.ignoreCameraViewport = true;
  93179. this._textures = [this._blurTexture1, this._blurTexture2];
  93180. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93181. width: blurTextureWidth,
  93182. height: blurTextureHeight
  93183. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93184. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  93185. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  93186. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  93187. effect.setTexture("textureSampler", _this._mainTexture);
  93188. });
  93189. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93190. width: blurTextureWidth,
  93191. height: blurTextureHeight
  93192. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93193. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93194. width: blurTextureWidth2,
  93195. height: blurTextureHeight2
  93196. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93197. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  93198. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  93199. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  93200. effect.setTexture("textureSampler", _this._blurTexture1);
  93201. });
  93202. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93203. width: blurTextureWidth2,
  93204. height: blurTextureHeight2
  93205. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93206. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93207. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  93208. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  93209. this._mainTexture.samples = this._options.mainTextureSamples;
  93210. this._mainTexture.onAfterUnbindObservable.add(function () {
  93211. var internalTexture = _this._blurTexture1.getInternalTexture();
  93212. if (internalTexture) {
  93213. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  93214. internalTexture = _this._blurTexture2.getInternalTexture();
  93215. if (internalTexture) {
  93216. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  93217. }
  93218. }
  93219. });
  93220. // Prevent autoClear.
  93221. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  93222. };
  93223. /**
  93224. * Checks for the readiness of the element composing the layer.
  93225. * @param subMesh the mesh to check for
  93226. * @param useInstances specify wether or not to use instances to render the mesh
  93227. * @param emissiveTexture the associated emissive texture used to generate the glow
  93228. * @return true if ready otherwise, false
  93229. */
  93230. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  93231. var material = subMesh.getMaterial();
  93232. var mesh = subMesh.getRenderingMesh();
  93233. if (!material || !mesh) {
  93234. return false;
  93235. }
  93236. var emissiveTexture = material.emissiveTexture;
  93237. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  93238. };
  93239. /**
  93240. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  93241. */
  93242. GlowLayer.prototype.needStencil = function () {
  93243. return false;
  93244. };
  93245. /**
  93246. * Implementation specific of rendering the generating effect on the main canvas.
  93247. * @param effect The effect used to render through
  93248. */
  93249. GlowLayer.prototype._internalRender = function (effect) {
  93250. // Texture
  93251. effect.setTexture("textureSampler", this._blurTexture1);
  93252. effect.setTexture("textureSampler2", this._blurTexture2);
  93253. effect.setFloat("offset", this._intensity);
  93254. // Cache
  93255. var engine = this._engine;
  93256. var previousStencilBuffer = engine.getStencilBuffer();
  93257. // Draw order
  93258. engine.setStencilBuffer(false);
  93259. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93260. // Draw order
  93261. engine.setStencilBuffer(previousStencilBuffer);
  93262. };
  93263. /**
  93264. * Sets the required values for both the emissive texture and and the main color.
  93265. */
  93266. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  93267. var textureLevel = 1.0;
  93268. if (this.customEmissiveTextureSelector) {
  93269. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  93270. }
  93271. else {
  93272. if (material) {
  93273. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  93274. if (this._emissiveTextureAndColor.texture) {
  93275. textureLevel = this._emissiveTextureAndColor.texture.level;
  93276. }
  93277. }
  93278. else {
  93279. this._emissiveTextureAndColor.texture = null;
  93280. }
  93281. }
  93282. if (this.customEmissiveColorSelector) {
  93283. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  93284. }
  93285. else {
  93286. if (material.emissiveColor) {
  93287. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  93288. }
  93289. else {
  93290. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  93291. }
  93292. }
  93293. };
  93294. /**
  93295. * Returns true if the mesh should render, otherwise false.
  93296. * @param mesh The mesh to render
  93297. * @returns true if it should render otherwise false
  93298. */
  93299. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  93300. return this.hasMesh(mesh);
  93301. };
  93302. /**
  93303. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  93304. * @param mesh The mesh to exclude from the glow layer
  93305. */
  93306. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  93307. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  93308. this._excludedMeshes.push(mesh.uniqueId);
  93309. }
  93310. };
  93311. /**
  93312. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  93313. * @param mesh The mesh to remove
  93314. */
  93315. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  93316. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  93317. if (index !== -1) {
  93318. this._excludedMeshes.splice(index, 1);
  93319. }
  93320. };
  93321. /**
  93322. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  93323. * @param mesh The mesh to include in the glow layer
  93324. */
  93325. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  93326. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  93327. this._includedOnlyMeshes.push(mesh.uniqueId);
  93328. }
  93329. };
  93330. /**
  93331. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  93332. * @param mesh The mesh to remove
  93333. */
  93334. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  93335. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  93336. if (index !== -1) {
  93337. this._includedOnlyMeshes.splice(index, 1);
  93338. }
  93339. };
  93340. /**
  93341. * Determine if a given mesh will be used in the glow layer
  93342. * @param mesh The mesh to test
  93343. * @returns true if the mesh will be highlighted by the current glow layer
  93344. */
  93345. GlowLayer.prototype.hasMesh = function (mesh) {
  93346. // Included Mesh
  93347. if (this._includedOnlyMeshes.length) {
  93348. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  93349. }
  93350. ;
  93351. // Excluded Mesh
  93352. if (this._excludedMeshes.length) {
  93353. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  93354. }
  93355. ;
  93356. return true;
  93357. };
  93358. /**
  93359. * Free any resources and references associated to a mesh.
  93360. * Internal use
  93361. * @param mesh The mesh to free.
  93362. */
  93363. GlowLayer.prototype._disposeMesh = function (mesh) {
  93364. this.removeIncludedOnlyMesh(mesh);
  93365. this.removeExcludedMesh(mesh);
  93366. };
  93367. /**
  93368. * Gets the class name of the effect layer
  93369. * @returns the string with the class name of the effect layer
  93370. */
  93371. GlowLayer.prototype.getClassName = function () {
  93372. return "GlowLayer";
  93373. };
  93374. /**
  93375. * Serializes this glow layer
  93376. * @returns a serialized glow layer object
  93377. */
  93378. GlowLayer.prototype.serialize = function () {
  93379. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93380. serializationObject.customType = "BABYLON.GlowLayer";
  93381. var index;
  93382. // Included meshes
  93383. serializationObject.includedMeshes = [];
  93384. if (this._includedOnlyMeshes.length) {
  93385. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  93386. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  93387. if (mesh) {
  93388. serializationObject.includedMeshes.push(mesh.id);
  93389. }
  93390. }
  93391. }
  93392. // Excluded meshes
  93393. serializationObject.excludedMeshes = [];
  93394. if (this._excludedMeshes.length) {
  93395. for (index = 0; index < this._excludedMeshes.length; index++) {
  93396. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  93397. if (mesh) {
  93398. serializationObject.excludedMeshes.push(mesh.id);
  93399. }
  93400. }
  93401. }
  93402. return serializationObject;
  93403. };
  93404. /**
  93405. * Creates a Glow Layer from parsed glow layer data
  93406. * @param parsedGlowLayer defines glow layer data
  93407. * @param scene defines the current scene
  93408. * @param rootUrl defines the root URL containing the glow layer information
  93409. * @returns a parsed Glow Layer
  93410. */
  93411. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  93412. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  93413. var index;
  93414. // Excluded meshes
  93415. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  93416. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  93417. if (mesh) {
  93418. gl.addExcludedMesh(mesh);
  93419. }
  93420. }
  93421. // Included meshes
  93422. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  93423. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  93424. if (mesh) {
  93425. gl.addIncludedOnlyMesh(mesh);
  93426. }
  93427. }
  93428. return gl;
  93429. };
  93430. /**
  93431. * Effect Name of the layer.
  93432. */
  93433. GlowLayer.EffectName = "GlowLayer";
  93434. /**
  93435. * The default blur kernel size used for the glow.
  93436. */
  93437. GlowLayer.DefaultBlurKernelSize = 32;
  93438. /**
  93439. * The default texture size ratio used for the glow.
  93440. */
  93441. GlowLayer.DefaultTextureRatio = 0.5;
  93442. __decorate([
  93443. BABYLON.serialize()
  93444. ], GlowLayer.prototype, "blurKernelSize", null);
  93445. __decorate([
  93446. BABYLON.serialize()
  93447. ], GlowLayer.prototype, "intensity", null);
  93448. __decorate([
  93449. BABYLON.serialize("options")
  93450. ], GlowLayer.prototype, "_options", void 0);
  93451. return GlowLayer;
  93452. }(BABYLON.EffectLayer));
  93453. BABYLON.GlowLayer = GlowLayer;
  93454. })(BABYLON || (BABYLON = {}));
  93455. //# sourceMappingURL=babylon.glowLayer.js.map
  93456. var BABYLON;
  93457. (function (BABYLON) {
  93458. /**
  93459. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  93460. */
  93461. var AssetTaskState;
  93462. (function (AssetTaskState) {
  93463. /**
  93464. * Initialization
  93465. */
  93466. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  93467. /**
  93468. * Running
  93469. */
  93470. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  93471. /**
  93472. * Done
  93473. */
  93474. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  93475. /**
  93476. * Error
  93477. */
  93478. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  93479. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  93480. /**
  93481. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  93482. */
  93483. var AbstractAssetTask = /** @class */ (function () {
  93484. /**
  93485. * Creates a new {BABYLON.AssetsManager}
  93486. * @param name defines the name of the task
  93487. */
  93488. function AbstractAssetTask(
  93489. /**
  93490. * Task name
  93491. */ name) {
  93492. this.name = name;
  93493. this._isCompleted = false;
  93494. this._taskState = AssetTaskState.INIT;
  93495. }
  93496. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  93497. /**
  93498. * Get if the task is completed
  93499. */
  93500. get: function () {
  93501. return this._isCompleted;
  93502. },
  93503. enumerable: true,
  93504. configurable: true
  93505. });
  93506. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  93507. /**
  93508. * Gets the current state of the task
  93509. */
  93510. get: function () {
  93511. return this._taskState;
  93512. },
  93513. enumerable: true,
  93514. configurable: true
  93515. });
  93516. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  93517. /**
  93518. * Gets the current error object (if task is in error)
  93519. */
  93520. get: function () {
  93521. return this._errorObject;
  93522. },
  93523. enumerable: true,
  93524. configurable: true
  93525. });
  93526. /**
  93527. * Internal only
  93528. * @hidden
  93529. */
  93530. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  93531. if (this._errorObject) {
  93532. return;
  93533. }
  93534. this._errorObject = {
  93535. message: message,
  93536. exception: exception
  93537. };
  93538. };
  93539. /**
  93540. * Execute the current task
  93541. * @param scene defines the scene where you want your assets to be loaded
  93542. * @param onSuccess is a callback called when the task is successfully executed
  93543. * @param onError is a callback called if an error occurs
  93544. */
  93545. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93546. var _this = this;
  93547. this._taskState = AssetTaskState.RUNNING;
  93548. this.runTask(scene, function () {
  93549. _this.onDoneCallback(onSuccess, onError);
  93550. }, function (msg, exception) {
  93551. _this.onErrorCallback(onError, msg, exception);
  93552. });
  93553. };
  93554. /**
  93555. * Execute the current task
  93556. * @param scene defines the scene where you want your assets to be loaded
  93557. * @param onSuccess is a callback called when the task is successfully executed
  93558. * @param onError is a callback called if an error occurs
  93559. */
  93560. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93561. throw new Error("runTask is not implemented");
  93562. };
  93563. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93564. this._taskState = AssetTaskState.ERROR;
  93565. this._errorObject = {
  93566. message: message,
  93567. exception: exception
  93568. };
  93569. if (this.onError) {
  93570. this.onError(this, message, exception);
  93571. }
  93572. onError();
  93573. };
  93574. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93575. try {
  93576. this._taskState = AssetTaskState.DONE;
  93577. this._isCompleted = true;
  93578. if (this.onSuccess) {
  93579. this.onSuccess(this);
  93580. }
  93581. onSuccess();
  93582. }
  93583. catch (e) {
  93584. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93585. }
  93586. };
  93587. return AbstractAssetTask;
  93588. }());
  93589. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93590. /**
  93591. * Class used to share progress information about assets loading
  93592. */
  93593. var AssetsProgressEvent = /** @class */ (function () {
  93594. /**
  93595. * Creates a {BABYLON.AssetsProgressEvent}
  93596. * @param remainingCount defines the number of remaining tasks to process
  93597. * @param totalCount defines the total number of tasks
  93598. * @param task defines the task that was just processed
  93599. */
  93600. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93601. this.remainingCount = remainingCount;
  93602. this.totalCount = totalCount;
  93603. this.task = task;
  93604. }
  93605. return AssetsProgressEvent;
  93606. }());
  93607. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93608. /**
  93609. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93610. */
  93611. var MeshAssetTask = /** @class */ (function (_super) {
  93612. __extends(MeshAssetTask, _super);
  93613. /**
  93614. * Creates a new {BABYLON.MeshAssetTask}
  93615. * @param name defines the name of the task
  93616. * @param meshesNames defines the list of mesh's names you want to load
  93617. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93618. * @param sceneFilename defines the filename of the scene to load from
  93619. */
  93620. function MeshAssetTask(
  93621. /**
  93622. * Defines the name of the task
  93623. */
  93624. name,
  93625. /**
  93626. * Defines the list of mesh's names you want to load
  93627. */
  93628. meshesNames,
  93629. /**
  93630. * Defines the root url to use as a base to load your meshes and associated resources
  93631. */
  93632. rootUrl,
  93633. /**
  93634. * Defines the filename of the scene to load from
  93635. */
  93636. sceneFilename) {
  93637. var _this = _super.call(this, name) || this;
  93638. _this.name = name;
  93639. _this.meshesNames = meshesNames;
  93640. _this.rootUrl = rootUrl;
  93641. _this.sceneFilename = sceneFilename;
  93642. return _this;
  93643. }
  93644. /**
  93645. * Execute the current task
  93646. * @param scene defines the scene where you want your assets to be loaded
  93647. * @param onSuccess is a callback called when the task is successfully executed
  93648. * @param onError is a callback called if an error occurs
  93649. */
  93650. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93651. var _this = this;
  93652. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93653. _this.loadedMeshes = meshes;
  93654. _this.loadedParticleSystems = particleSystems;
  93655. _this.loadedSkeletons = skeletons;
  93656. onSuccess();
  93657. }, null, function (scene, message, exception) {
  93658. onError(message, exception);
  93659. });
  93660. };
  93661. return MeshAssetTask;
  93662. }(AbstractAssetTask));
  93663. BABYLON.MeshAssetTask = MeshAssetTask;
  93664. /**
  93665. * Define a task used by {BABYLON.AssetsManager} to load text content
  93666. */
  93667. var TextFileAssetTask = /** @class */ (function (_super) {
  93668. __extends(TextFileAssetTask, _super);
  93669. /**
  93670. * Creates a new TextFileAssetTask object
  93671. * @param name defines the name of the task
  93672. * @param url defines the location of the file to load
  93673. */
  93674. function TextFileAssetTask(
  93675. /**
  93676. * Defines the name of the task
  93677. */
  93678. name,
  93679. /**
  93680. * Defines the location of the file to load
  93681. */
  93682. url) {
  93683. var _this = _super.call(this, name) || this;
  93684. _this.name = name;
  93685. _this.url = url;
  93686. return _this;
  93687. }
  93688. /**
  93689. * Execute the current task
  93690. * @param scene defines the scene where you want your assets to be loaded
  93691. * @param onSuccess is a callback called when the task is successfully executed
  93692. * @param onError is a callback called if an error occurs
  93693. */
  93694. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93695. var _this = this;
  93696. scene._loadFile(this.url, function (data) {
  93697. _this.text = data;
  93698. onSuccess();
  93699. }, undefined, false, false, function (request, exception) {
  93700. if (request) {
  93701. onError(request.status + " " + request.statusText, exception);
  93702. }
  93703. });
  93704. };
  93705. return TextFileAssetTask;
  93706. }(AbstractAssetTask));
  93707. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93708. /**
  93709. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93710. */
  93711. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93712. __extends(BinaryFileAssetTask, _super);
  93713. /**
  93714. * Creates a new BinaryFileAssetTask object
  93715. * @param name defines the name of the new task
  93716. * @param url defines the location of the file to load
  93717. */
  93718. function BinaryFileAssetTask(
  93719. /**
  93720. * Defines the name of the task
  93721. */
  93722. name,
  93723. /**
  93724. * Defines the location of the file to load
  93725. */
  93726. url) {
  93727. var _this = _super.call(this, name) || this;
  93728. _this.name = name;
  93729. _this.url = url;
  93730. return _this;
  93731. }
  93732. /**
  93733. * Execute the current task
  93734. * @param scene defines the scene where you want your assets to be loaded
  93735. * @param onSuccess is a callback called when the task is successfully executed
  93736. * @param onError is a callback called if an error occurs
  93737. */
  93738. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93739. var _this = this;
  93740. scene._loadFile(this.url, function (data) {
  93741. _this.data = data;
  93742. onSuccess();
  93743. }, undefined, true, true, function (request, exception) {
  93744. if (request) {
  93745. onError(request.status + " " + request.statusText, exception);
  93746. }
  93747. });
  93748. };
  93749. return BinaryFileAssetTask;
  93750. }(AbstractAssetTask));
  93751. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93752. /**
  93753. * Define a task used by {BABYLON.AssetsManager} to load images
  93754. */
  93755. var ImageAssetTask = /** @class */ (function (_super) {
  93756. __extends(ImageAssetTask, _super);
  93757. /**
  93758. * Creates a new ImageAssetTask
  93759. * @param name defines the name of the task
  93760. * @param url defines the location of the image to load
  93761. */
  93762. function ImageAssetTask(
  93763. /**
  93764. * Defines the name of the task
  93765. */
  93766. name,
  93767. /**
  93768. * Defines the location of the image to load
  93769. */
  93770. url) {
  93771. var _this = _super.call(this, name) || this;
  93772. _this.name = name;
  93773. _this.url = url;
  93774. return _this;
  93775. }
  93776. /**
  93777. * Execute the current task
  93778. * @param scene defines the scene where you want your assets to be loaded
  93779. * @param onSuccess is a callback called when the task is successfully executed
  93780. * @param onError is a callback called if an error occurs
  93781. */
  93782. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93783. var _this = this;
  93784. var img = new Image();
  93785. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93786. img.onload = function () {
  93787. _this.image = img;
  93788. onSuccess();
  93789. };
  93790. img.onerror = function (err) {
  93791. onError("Error loading image", err);
  93792. };
  93793. img.src = this.url;
  93794. };
  93795. return ImageAssetTask;
  93796. }(AbstractAssetTask));
  93797. BABYLON.ImageAssetTask = ImageAssetTask;
  93798. /**
  93799. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93800. */
  93801. var TextureAssetTask = /** @class */ (function (_super) {
  93802. __extends(TextureAssetTask, _super);
  93803. /**
  93804. * Creates a new TextureAssetTask object
  93805. * @param name defines the name of the task
  93806. * @param url defines the location of the file to load
  93807. * @param noMipmap defines if mipmap should not be generated (default is false)
  93808. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93809. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93810. */
  93811. function TextureAssetTask(
  93812. /**
  93813. * Defines the name of the task
  93814. */
  93815. name,
  93816. /**
  93817. * Defines the location of the file to load
  93818. */
  93819. url,
  93820. /**
  93821. * Defines if mipmap should not be generated (default is false)
  93822. */
  93823. noMipmap,
  93824. /**
  93825. * Defines if texture must be inverted on Y axis (default is false)
  93826. */
  93827. invertY,
  93828. /**
  93829. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93830. */
  93831. samplingMode) {
  93832. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93833. var _this = _super.call(this, name) || this;
  93834. _this.name = name;
  93835. _this.url = url;
  93836. _this.noMipmap = noMipmap;
  93837. _this.invertY = invertY;
  93838. _this.samplingMode = samplingMode;
  93839. return _this;
  93840. }
  93841. /**
  93842. * Execute the current task
  93843. * @param scene defines the scene where you want your assets to be loaded
  93844. * @param onSuccess is a callback called when the task is successfully executed
  93845. * @param onError is a callback called if an error occurs
  93846. */
  93847. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93848. var onload = function () {
  93849. onSuccess();
  93850. };
  93851. var onerror = function (message, exception) {
  93852. onError(message, exception);
  93853. };
  93854. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93855. };
  93856. return TextureAssetTask;
  93857. }(AbstractAssetTask));
  93858. BABYLON.TextureAssetTask = TextureAssetTask;
  93859. /**
  93860. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93861. */
  93862. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93863. __extends(CubeTextureAssetTask, _super);
  93864. /**
  93865. * Creates a new CubeTextureAssetTask
  93866. * @param name defines the name of the task
  93867. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93868. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93869. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93870. * @param files defines the explicit list of files (undefined by default)
  93871. */
  93872. function CubeTextureAssetTask(
  93873. /**
  93874. * Defines the name of the task
  93875. */
  93876. name,
  93877. /**
  93878. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93879. */
  93880. url,
  93881. /**
  93882. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93883. */
  93884. extensions,
  93885. /**
  93886. * Defines if mipmaps should not be generated (default is false)
  93887. */
  93888. noMipmap,
  93889. /**
  93890. * Defines the explicit list of files (undefined by default)
  93891. */
  93892. files) {
  93893. var _this = _super.call(this, name) || this;
  93894. _this.name = name;
  93895. _this.url = url;
  93896. _this.extensions = extensions;
  93897. _this.noMipmap = noMipmap;
  93898. _this.files = files;
  93899. return _this;
  93900. }
  93901. /**
  93902. * Execute the current task
  93903. * @param scene defines the scene where you want your assets to be loaded
  93904. * @param onSuccess is a callback called when the task is successfully executed
  93905. * @param onError is a callback called if an error occurs
  93906. */
  93907. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93908. var onload = function () {
  93909. onSuccess();
  93910. };
  93911. var onerror = function (message, exception) {
  93912. onError(message, exception);
  93913. };
  93914. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93915. };
  93916. return CubeTextureAssetTask;
  93917. }(AbstractAssetTask));
  93918. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93919. /**
  93920. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93921. */
  93922. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93923. __extends(HDRCubeTextureAssetTask, _super);
  93924. /**
  93925. * Creates a new HDRCubeTextureAssetTask object
  93926. * @param name defines the name of the task
  93927. * @param url defines the location of the file to load
  93928. * @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.
  93929. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93930. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93931. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93932. * @param reserved Internal use only
  93933. */
  93934. function HDRCubeTextureAssetTask(
  93935. /**
  93936. * Defines the name of the task
  93937. */
  93938. name,
  93939. /**
  93940. * Defines the location of the file to load
  93941. */
  93942. url,
  93943. /**
  93944. * Defines the desired size (the more it increases the longer the generation will be)
  93945. */
  93946. size,
  93947. /**
  93948. * Defines if mipmaps should not be generated (default is false)
  93949. */
  93950. noMipmap,
  93951. /**
  93952. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93953. */
  93954. generateHarmonics,
  93955. /**
  93956. * 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)
  93957. */
  93958. gammaSpace,
  93959. /**
  93960. * Internal Use Only
  93961. */
  93962. reserved) {
  93963. if (noMipmap === void 0) { noMipmap = false; }
  93964. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93965. if (gammaSpace === void 0) { gammaSpace = false; }
  93966. if (reserved === void 0) { reserved = false; }
  93967. var _this = _super.call(this, name) || this;
  93968. _this.name = name;
  93969. _this.url = url;
  93970. _this.size = size;
  93971. _this.noMipmap = noMipmap;
  93972. _this.generateHarmonics = generateHarmonics;
  93973. _this.gammaSpace = gammaSpace;
  93974. _this.reserved = reserved;
  93975. return _this;
  93976. }
  93977. /**
  93978. * Execute the current task
  93979. * @param scene defines the scene where you want your assets to be loaded
  93980. * @param onSuccess is a callback called when the task is successfully executed
  93981. * @param onError is a callback called if an error occurs
  93982. */
  93983. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93984. var onload = function () {
  93985. onSuccess();
  93986. };
  93987. var onerror = function (message, exception) {
  93988. onError(message, exception);
  93989. };
  93990. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93991. };
  93992. return HDRCubeTextureAssetTask;
  93993. }(AbstractAssetTask));
  93994. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93995. /**
  93996. * This class can be used to easily import assets into a scene
  93997. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93998. */
  93999. var AssetsManager = /** @class */ (function () {
  94000. /**
  94001. * Creates a new AssetsManager
  94002. * @param scene defines the scene to work on
  94003. */
  94004. function AssetsManager(scene) {
  94005. this._isLoading = false;
  94006. this._tasks = new Array();
  94007. this._waitingTasksCount = 0;
  94008. this._totalTasksCount = 0;
  94009. /**
  94010. * Observable called when all tasks are processed
  94011. */
  94012. this.onTaskSuccessObservable = new BABYLON.Observable();
  94013. /**
  94014. * Observable called when a task had an error
  94015. */
  94016. this.onTaskErrorObservable = new BABYLON.Observable();
  94017. /**
  94018. * Observable called when a task is successful
  94019. */
  94020. this.onTasksDoneObservable = new BABYLON.Observable();
  94021. /**
  94022. * Observable called when a task is done (whatever the result is)
  94023. */
  94024. this.onProgressObservable = new BABYLON.Observable();
  94025. /**
  94026. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  94027. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  94028. */
  94029. this.useDefaultLoadingScreen = true;
  94030. this._scene = scene;
  94031. }
  94032. /**
  94033. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  94034. * @param taskName defines the name of the new task
  94035. * @param meshesNames defines the name of meshes to load
  94036. * @param rootUrl defines the root url to use to locate files
  94037. * @param sceneFilename defines the filename of the scene file
  94038. * @returns a new {BABYLON.MeshAssetTask} object
  94039. */
  94040. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  94041. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  94042. this._tasks.push(task);
  94043. return task;
  94044. };
  94045. /**
  94046. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  94047. * @param taskName defines the name of the new task
  94048. * @param url defines the url of the file to load
  94049. * @returns a new {BABYLON.TextFileAssetTask} object
  94050. */
  94051. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  94052. var task = new TextFileAssetTask(taskName, url);
  94053. this._tasks.push(task);
  94054. return task;
  94055. };
  94056. /**
  94057. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  94058. * @param taskName defines the name of the new task
  94059. * @param url defines the url of the file to load
  94060. * @returns a new {BABYLON.BinaryFileAssetTask} object
  94061. */
  94062. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  94063. var task = new BinaryFileAssetTask(taskName, url);
  94064. this._tasks.push(task);
  94065. return task;
  94066. };
  94067. /**
  94068. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  94069. * @param taskName defines the name of the new task
  94070. * @param url defines the url of the file to load
  94071. * @returns a new {BABYLON.ImageAssetTask} object
  94072. */
  94073. AssetsManager.prototype.addImageTask = function (taskName, url) {
  94074. var task = new ImageAssetTask(taskName, url);
  94075. this._tasks.push(task);
  94076. return task;
  94077. };
  94078. /**
  94079. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  94080. * @param taskName defines the name of the new task
  94081. * @param url defines the url of the file to load
  94082. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94083. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  94084. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  94085. * @returns a new {BABYLON.TextureAssetTask} object
  94086. */
  94087. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  94088. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94089. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  94090. this._tasks.push(task);
  94091. return task;
  94092. };
  94093. /**
  94094. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  94095. * @param taskName defines the name of the new task
  94096. * @param url defines the url of the file to load
  94097. * @param extensions defines the extension to use to load the cube map (can be null)
  94098. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94099. * @param files defines the list of files to load (can be null)
  94100. * @returns a new {BABYLON.CubeTextureAssetTask} object
  94101. */
  94102. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  94103. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  94104. this._tasks.push(task);
  94105. return task;
  94106. };
  94107. /**
  94108. *
  94109. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  94110. * @param taskName defines the name of the new task
  94111. * @param url defines the url of the file to load
  94112. * @param size defines the size you want for the cubemap (can be null)
  94113. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94114. * @param generateHarmonics defines if you want to automatically generate (true by default)
  94115. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  94116. * @param reserved Internal use only
  94117. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  94118. */
  94119. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  94120. if (noMipmap === void 0) { noMipmap = false; }
  94121. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94122. if (gammaSpace === void 0) { gammaSpace = false; }
  94123. if (reserved === void 0) { reserved = false; }
  94124. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  94125. this._tasks.push(task);
  94126. return task;
  94127. };
  94128. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  94129. this._waitingTasksCount--;
  94130. try {
  94131. if (this.onProgress) {
  94132. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  94133. }
  94134. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  94135. }
  94136. catch (e) {
  94137. BABYLON.Tools.Error("Error running progress callbacks.");
  94138. console.log(e);
  94139. }
  94140. if (this._waitingTasksCount === 0) {
  94141. try {
  94142. if (this.onFinish) {
  94143. this.onFinish(this._tasks);
  94144. }
  94145. // Let's remove successfull tasks
  94146. var currentTasks = this._tasks.slice();
  94147. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  94148. var task = currentTasks_1[_i];
  94149. if (task.taskState === AssetTaskState.DONE) {
  94150. var index = this._tasks.indexOf(task);
  94151. if (index > -1) {
  94152. this._tasks.splice(index, 1);
  94153. }
  94154. }
  94155. }
  94156. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94157. }
  94158. catch (e) {
  94159. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  94160. console.log(e);
  94161. }
  94162. this._isLoading = false;
  94163. this._scene.getEngine().hideLoadingUI();
  94164. }
  94165. };
  94166. AssetsManager.prototype._runTask = function (task) {
  94167. var _this = this;
  94168. var done = function () {
  94169. try {
  94170. if (_this.onTaskSuccess) {
  94171. _this.onTaskSuccess(task);
  94172. }
  94173. _this.onTaskSuccessObservable.notifyObservers(task);
  94174. _this._decreaseWaitingTasksCount(task);
  94175. }
  94176. catch (e) {
  94177. error("Error executing task success callbacks", e);
  94178. }
  94179. };
  94180. var error = function (message, exception) {
  94181. task._setErrorObject(message, exception);
  94182. if (_this.onTaskError) {
  94183. _this.onTaskError(task);
  94184. }
  94185. _this.onTaskErrorObservable.notifyObservers(task);
  94186. _this._decreaseWaitingTasksCount(task);
  94187. };
  94188. task.run(this._scene, done, error);
  94189. };
  94190. /**
  94191. * Reset the {BABYLON.AssetsManager} and remove all tasks
  94192. * @return the current instance of the {BABYLON.AssetsManager}
  94193. */
  94194. AssetsManager.prototype.reset = function () {
  94195. this._isLoading = false;
  94196. this._tasks = new Array();
  94197. return this;
  94198. };
  94199. /**
  94200. * Start the loading process
  94201. * @return the current instance of the {BABYLON.AssetsManager}
  94202. */
  94203. AssetsManager.prototype.load = function () {
  94204. if (this._isLoading) {
  94205. return this;
  94206. }
  94207. this._isLoading = true;
  94208. this._waitingTasksCount = this._tasks.length;
  94209. this._totalTasksCount = this._tasks.length;
  94210. if (this._waitingTasksCount === 0) {
  94211. this._isLoading = false;
  94212. if (this.onFinish) {
  94213. this.onFinish(this._tasks);
  94214. }
  94215. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94216. return this;
  94217. }
  94218. if (this.useDefaultLoadingScreen) {
  94219. this._scene.getEngine().displayLoadingUI();
  94220. }
  94221. for (var index = 0; index < this._tasks.length; index++) {
  94222. var task = this._tasks[index];
  94223. this._runTask(task);
  94224. }
  94225. return this;
  94226. };
  94227. return AssetsManager;
  94228. }());
  94229. BABYLON.AssetsManager = AssetsManager;
  94230. })(BABYLON || (BABYLON = {}));
  94231. //# sourceMappingURL=babylon.assetsManager.js.map
  94232. var BABYLON;
  94233. (function (BABYLON) {
  94234. var serializedGeometries = [];
  94235. var serializeGeometry = function (geometry, serializationGeometries) {
  94236. if (serializedGeometries[geometry.id]) {
  94237. return;
  94238. }
  94239. if (geometry.doNotSerialize) {
  94240. return;
  94241. }
  94242. if (geometry instanceof BABYLON.BoxGeometry) {
  94243. serializationGeometries.boxes.push(geometry.serialize());
  94244. }
  94245. else if (geometry instanceof BABYLON.SphereGeometry) {
  94246. serializationGeometries.spheres.push(geometry.serialize());
  94247. }
  94248. else if (geometry instanceof BABYLON.CylinderGeometry) {
  94249. serializationGeometries.cylinders.push(geometry.serialize());
  94250. }
  94251. else if (geometry instanceof BABYLON.TorusGeometry) {
  94252. serializationGeometries.toruses.push(geometry.serialize());
  94253. }
  94254. else if (geometry instanceof BABYLON.GroundGeometry) {
  94255. serializationGeometries.grounds.push(geometry.serialize());
  94256. }
  94257. else if (geometry instanceof BABYLON.Plane) {
  94258. serializationGeometries.planes.push(geometry.serialize());
  94259. }
  94260. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  94261. serializationGeometries.torusKnots.push(geometry.serialize());
  94262. }
  94263. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  94264. throw new Error("Unknown primitive type");
  94265. }
  94266. else {
  94267. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  94268. }
  94269. serializedGeometries[geometry.id] = true;
  94270. };
  94271. var serializeMesh = function (mesh, serializationScene) {
  94272. var serializationObject = {};
  94273. // Geometry
  94274. var geometry = mesh._geometry;
  94275. if (geometry) {
  94276. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  94277. // 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
  94278. serializeGeometry(geometry, serializationScene.geometries);
  94279. }
  94280. }
  94281. // Custom
  94282. if (mesh.serialize) {
  94283. mesh.serialize(serializationObject);
  94284. }
  94285. return serializationObject;
  94286. };
  94287. var finalizeSingleMesh = function (mesh, serializationObject) {
  94288. //only works if the mesh is already loaded
  94289. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94290. //serialize material
  94291. if (mesh.material) {
  94292. if (mesh.material instanceof BABYLON.StandardMaterial) {
  94293. serializationObject.materials = serializationObject.materials || [];
  94294. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94295. serializationObject.materials.push(mesh.material.serialize());
  94296. }
  94297. }
  94298. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  94299. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  94300. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  94301. serializationObject.multiMaterials.push(mesh.material.serialize());
  94302. }
  94303. }
  94304. }
  94305. //serialize geometry
  94306. var geometry = mesh._geometry;
  94307. if (geometry) {
  94308. if (!serializationObject.geometries) {
  94309. serializationObject.geometries = {};
  94310. serializationObject.geometries.boxes = [];
  94311. serializationObject.geometries.spheres = [];
  94312. serializationObject.geometries.cylinders = [];
  94313. serializationObject.geometries.toruses = [];
  94314. serializationObject.geometries.grounds = [];
  94315. serializationObject.geometries.planes = [];
  94316. serializationObject.geometries.torusKnots = [];
  94317. serializationObject.geometries.vertexData = [];
  94318. }
  94319. serializeGeometry(geometry, serializationObject.geometries);
  94320. }
  94321. // Skeletons
  94322. if (mesh.skeleton) {
  94323. serializationObject.skeletons = serializationObject.skeletons || [];
  94324. serializationObject.skeletons.push(mesh.skeleton.serialize());
  94325. }
  94326. //serialize the actual mesh
  94327. serializationObject.meshes = serializationObject.meshes || [];
  94328. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94329. }
  94330. };
  94331. var SceneSerializer = /** @class */ (function () {
  94332. function SceneSerializer() {
  94333. }
  94334. SceneSerializer.ClearCache = function () {
  94335. serializedGeometries = [];
  94336. };
  94337. SceneSerializer.Serialize = function (scene) {
  94338. var serializationObject = {};
  94339. SceneSerializer.ClearCache();
  94340. // Scene
  94341. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  94342. serializationObject.autoClear = scene.autoClear;
  94343. serializationObject.clearColor = scene.clearColor.asArray();
  94344. serializationObject.ambientColor = scene.ambientColor.asArray();
  94345. serializationObject.gravity = scene.gravity.asArray();
  94346. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  94347. serializationObject.workerCollisions = scene.workerCollisions;
  94348. // Fog
  94349. if (scene.fogMode && scene.fogMode !== 0) {
  94350. serializationObject.fogMode = scene.fogMode;
  94351. serializationObject.fogColor = scene.fogColor.asArray();
  94352. serializationObject.fogStart = scene.fogStart;
  94353. serializationObject.fogEnd = scene.fogEnd;
  94354. serializationObject.fogDensity = scene.fogDensity;
  94355. }
  94356. //Physics
  94357. if (scene.isPhysicsEnabled()) {
  94358. var physicEngine = scene.getPhysicsEngine();
  94359. if (physicEngine) {
  94360. serializationObject.physicsEnabled = true;
  94361. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  94362. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  94363. }
  94364. }
  94365. // Metadata
  94366. if (scene.metadata) {
  94367. serializationObject.metadata = scene.metadata;
  94368. }
  94369. // Morph targets
  94370. serializationObject.morphTargetManagers = [];
  94371. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  94372. var abstractMesh = _a[_i];
  94373. var manager = abstractMesh.morphTargetManager;
  94374. if (manager) {
  94375. serializationObject.morphTargetManagers.push(manager.serialize());
  94376. }
  94377. }
  94378. // Lights
  94379. serializationObject.lights = [];
  94380. var index;
  94381. var light;
  94382. for (index = 0; index < scene.lights.length; index++) {
  94383. light = scene.lights[index];
  94384. if (!light.doNotSerialize) {
  94385. serializationObject.lights.push(light.serialize());
  94386. }
  94387. }
  94388. // Cameras
  94389. serializationObject.cameras = [];
  94390. for (index = 0; index < scene.cameras.length; index++) {
  94391. var camera = scene.cameras[index];
  94392. if (!camera.doNotSerialize) {
  94393. serializationObject.cameras.push(camera.serialize());
  94394. }
  94395. }
  94396. if (scene.activeCamera) {
  94397. serializationObject.activeCameraID = scene.activeCamera.id;
  94398. }
  94399. // Animations
  94400. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  94401. // Materials
  94402. serializationObject.materials = [];
  94403. serializationObject.multiMaterials = [];
  94404. var material;
  94405. for (index = 0; index < scene.materials.length; index++) {
  94406. material = scene.materials[index];
  94407. if (!material.doNotSerialize) {
  94408. serializationObject.materials.push(material.serialize());
  94409. }
  94410. }
  94411. // MultiMaterials
  94412. serializationObject.multiMaterials = [];
  94413. for (index = 0; index < scene.multiMaterials.length; index++) {
  94414. var multiMaterial = scene.multiMaterials[index];
  94415. serializationObject.multiMaterials.push(multiMaterial.serialize());
  94416. }
  94417. // Environment texture
  94418. if (scene.environmentTexture) {
  94419. serializationObject.environmentTexture = scene.environmentTexture.name;
  94420. }
  94421. // Skeletons
  94422. serializationObject.skeletons = [];
  94423. for (index = 0; index < scene.skeletons.length; index++) {
  94424. var skeleton = scene.skeletons[index];
  94425. if (!skeleton.doNotSerialize) {
  94426. serializationObject.skeletons.push(skeleton.serialize());
  94427. }
  94428. }
  94429. // Transform nodes
  94430. serializationObject.transformNodes = [];
  94431. for (index = 0; index < scene.transformNodes.length; index++) {
  94432. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  94433. }
  94434. // Geometries
  94435. serializationObject.geometries = {};
  94436. serializationObject.geometries.boxes = [];
  94437. serializationObject.geometries.spheres = [];
  94438. serializationObject.geometries.cylinders = [];
  94439. serializationObject.geometries.toruses = [];
  94440. serializationObject.geometries.grounds = [];
  94441. serializationObject.geometries.planes = [];
  94442. serializationObject.geometries.torusKnots = [];
  94443. serializationObject.geometries.vertexData = [];
  94444. serializedGeometries = [];
  94445. var geometries = scene.getGeometries();
  94446. for (index = 0; index < geometries.length; index++) {
  94447. var geometry = geometries[index];
  94448. if (geometry.isReady()) {
  94449. serializeGeometry(geometry, serializationObject.geometries);
  94450. }
  94451. }
  94452. // Meshes
  94453. serializationObject.meshes = [];
  94454. for (index = 0; index < scene.meshes.length; index++) {
  94455. var abstractMesh = scene.meshes[index];
  94456. if (abstractMesh instanceof BABYLON.Mesh) {
  94457. var mesh = abstractMesh;
  94458. if (!mesh.doNotSerialize) {
  94459. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94460. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94461. }
  94462. }
  94463. }
  94464. }
  94465. // Particles Systems
  94466. serializationObject.particleSystems = [];
  94467. for (index = 0; index < scene.particleSystems.length; index++) {
  94468. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  94469. }
  94470. // Lens flares
  94471. serializationObject.lensFlareSystems = [];
  94472. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  94473. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  94474. }
  94475. // Shadows
  94476. serializationObject.shadowGenerators = [];
  94477. for (index = 0; index < scene.lights.length; index++) {
  94478. light = scene.lights[index];
  94479. var shadowGenerator = light.getShadowGenerator();
  94480. if (shadowGenerator) {
  94481. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  94482. }
  94483. }
  94484. // Action Manager
  94485. if (scene.actionManager) {
  94486. serializationObject.actions = scene.actionManager.serialize("scene");
  94487. }
  94488. // Audio
  94489. serializationObject.sounds = [];
  94490. for (index = 0; index < scene.soundTracks.length; index++) {
  94491. var soundtrack = scene.soundTracks[index];
  94492. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  94493. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  94494. }
  94495. }
  94496. // Effect layers
  94497. serializationObject.effectLayers = [];
  94498. for (index = 0; index < scene.effectLayers.length; index++) {
  94499. var layer = scene.effectLayers[index];
  94500. if (layer.serialize) {
  94501. serializationObject.effectLayers.push(layer.serialize());
  94502. }
  94503. }
  94504. return serializationObject;
  94505. };
  94506. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  94507. if (withParents === void 0) { withParents = false; }
  94508. if (withChildren === void 0) { withChildren = false; }
  94509. var serializationObject = {};
  94510. SceneSerializer.ClearCache();
  94511. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  94512. if (withParents || withChildren) {
  94513. //deliberate for loop! not for each, appended should be processed as well.
  94514. for (var i = 0; i < toSerialize.length; ++i) {
  94515. if (withChildren) {
  94516. toSerialize[i].getDescendants().forEach(function (node) {
  94517. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  94518. toSerialize.push(node);
  94519. }
  94520. });
  94521. }
  94522. //make sure the array doesn't contain the object already
  94523. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  94524. toSerialize.push(toSerialize[i].parent);
  94525. }
  94526. }
  94527. }
  94528. toSerialize.forEach(function (mesh) {
  94529. finalizeSingleMesh(mesh, serializationObject);
  94530. });
  94531. return serializationObject;
  94532. };
  94533. return SceneSerializer;
  94534. }());
  94535. BABYLON.SceneSerializer = SceneSerializer;
  94536. })(BABYLON || (BABYLON = {}));
  94537. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94538. var BABYLON;
  94539. (function (BABYLON) {
  94540. var ReflectionProbe = /** @class */ (function () {
  94541. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94542. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94543. var _this = this;
  94544. this.name = name;
  94545. this._viewMatrix = BABYLON.Matrix.Identity();
  94546. this._target = BABYLON.Vector3.Zero();
  94547. this._add = BABYLON.Vector3.Zero();
  94548. this._invertYAxis = false;
  94549. this.position = BABYLON.Vector3.Zero();
  94550. this._scene = scene;
  94551. this._scene.reflectionProbes.push(this);
  94552. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94553. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94554. switch (faceIndex) {
  94555. case 0:
  94556. _this._add.copyFromFloats(1, 0, 0);
  94557. break;
  94558. case 1:
  94559. _this._add.copyFromFloats(-1, 0, 0);
  94560. break;
  94561. case 2:
  94562. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94563. break;
  94564. case 3:
  94565. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94566. break;
  94567. case 4:
  94568. _this._add.copyFromFloats(0, 0, 1);
  94569. break;
  94570. case 5:
  94571. _this._add.copyFromFloats(0, 0, -1);
  94572. break;
  94573. }
  94574. if (_this._attachedMesh) {
  94575. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94576. }
  94577. _this.position.addToRef(_this._add, _this._target);
  94578. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94579. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94580. scene._forcedViewPosition = _this.position;
  94581. });
  94582. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94583. scene._forcedViewPosition = null;
  94584. scene.updateTransformMatrix(true);
  94585. });
  94586. if (scene.activeCamera) {
  94587. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94588. }
  94589. }
  94590. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94591. get: function () {
  94592. return this._renderTargetTexture.samples;
  94593. },
  94594. set: function (value) {
  94595. this._renderTargetTexture.samples = value;
  94596. },
  94597. enumerable: true,
  94598. configurable: true
  94599. });
  94600. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94601. get: function () {
  94602. return this._renderTargetTexture.refreshRate;
  94603. },
  94604. set: function (value) {
  94605. this._renderTargetTexture.refreshRate = value;
  94606. },
  94607. enumerable: true,
  94608. configurable: true
  94609. });
  94610. ReflectionProbe.prototype.getScene = function () {
  94611. return this._scene;
  94612. };
  94613. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94614. get: function () {
  94615. return this._renderTargetTexture;
  94616. },
  94617. enumerable: true,
  94618. configurable: true
  94619. });
  94620. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94621. get: function () {
  94622. return this._renderTargetTexture.renderList;
  94623. },
  94624. enumerable: true,
  94625. configurable: true
  94626. });
  94627. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94628. this._attachedMesh = mesh;
  94629. };
  94630. /**
  94631. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94632. *
  94633. * @param renderingGroupId The rendering group id corresponding to its index
  94634. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94635. */
  94636. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94637. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94638. };
  94639. ReflectionProbe.prototype.dispose = function () {
  94640. var index = this._scene.reflectionProbes.indexOf(this);
  94641. if (index !== -1) {
  94642. // Remove from the scene if found
  94643. this._scene.reflectionProbes.splice(index, 1);
  94644. }
  94645. if (this._renderTargetTexture) {
  94646. this._renderTargetTexture.dispose();
  94647. this._renderTargetTexture = null;
  94648. }
  94649. };
  94650. return ReflectionProbe;
  94651. }());
  94652. BABYLON.ReflectionProbe = ReflectionProbe;
  94653. })(BABYLON || (BABYLON = {}));
  94654. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94655. var BABYLON;
  94656. (function (BABYLON) {
  94657. var Layer = /** @class */ (function () {
  94658. function Layer(name, imgUrl, scene, isBackground, color) {
  94659. this.name = name;
  94660. this.scale = new BABYLON.Vector2(1, 1);
  94661. this.offset = new BABYLON.Vector2(0, 0);
  94662. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94663. this.layerMask = 0x0FFFFFFF;
  94664. this._vertexBuffers = {};
  94665. // Events
  94666. /**
  94667. * An event triggered when the layer is disposed.
  94668. */
  94669. this.onDisposeObservable = new BABYLON.Observable();
  94670. /**
  94671. * An event triggered before rendering the scene
  94672. */
  94673. this.onBeforeRenderObservable = new BABYLON.Observable();
  94674. /**
  94675. * An event triggered after rendering the scene
  94676. */
  94677. this.onAfterRenderObservable = new BABYLON.Observable();
  94678. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94679. this.isBackground = isBackground === undefined ? true : isBackground;
  94680. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94681. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94682. this._scene.layers.push(this);
  94683. var engine = this._scene.getEngine();
  94684. // VBO
  94685. var vertices = [];
  94686. vertices.push(1, 1);
  94687. vertices.push(-1, 1);
  94688. vertices.push(-1, -1);
  94689. vertices.push(1, -1);
  94690. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94691. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94692. this._createIndexBuffer();
  94693. // Effects
  94694. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94695. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94696. }
  94697. Object.defineProperty(Layer.prototype, "onDispose", {
  94698. set: function (callback) {
  94699. if (this._onDisposeObserver) {
  94700. this.onDisposeObservable.remove(this._onDisposeObserver);
  94701. }
  94702. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94703. },
  94704. enumerable: true,
  94705. configurable: true
  94706. });
  94707. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94708. set: function (callback) {
  94709. if (this._onBeforeRenderObserver) {
  94710. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94711. }
  94712. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94713. },
  94714. enumerable: true,
  94715. configurable: true
  94716. });
  94717. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94718. set: function (callback) {
  94719. if (this._onAfterRenderObserver) {
  94720. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94721. }
  94722. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94723. },
  94724. enumerable: true,
  94725. configurable: true
  94726. });
  94727. Layer.prototype._createIndexBuffer = function () {
  94728. var engine = this._scene.getEngine();
  94729. // Indices
  94730. var indices = [];
  94731. indices.push(0);
  94732. indices.push(1);
  94733. indices.push(2);
  94734. indices.push(0);
  94735. indices.push(2);
  94736. indices.push(3);
  94737. this._indexBuffer = engine.createIndexBuffer(indices);
  94738. };
  94739. Layer.prototype._rebuild = function () {
  94740. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94741. if (vb) {
  94742. vb._rebuild();
  94743. }
  94744. this._createIndexBuffer();
  94745. };
  94746. Layer.prototype.render = function () {
  94747. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94748. // Check
  94749. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94750. return;
  94751. var engine = this._scene.getEngine();
  94752. this.onBeforeRenderObservable.notifyObservers(this);
  94753. // Render
  94754. engine.enableEffect(currentEffect);
  94755. engine.setState(false);
  94756. // Texture
  94757. currentEffect.setTexture("textureSampler", this.texture);
  94758. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94759. // Color
  94760. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94761. // Scale / offset
  94762. currentEffect.setVector2("offset", this.offset);
  94763. currentEffect.setVector2("scale", this.scale);
  94764. // VBOs
  94765. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94766. // Draw order
  94767. if (!this.alphaTest) {
  94768. engine.setAlphaMode(this.alphaBlendingMode);
  94769. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94770. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94771. }
  94772. else {
  94773. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94774. }
  94775. this.onAfterRenderObservable.notifyObservers(this);
  94776. };
  94777. Layer.prototype.dispose = function () {
  94778. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94779. if (vertexBuffer) {
  94780. vertexBuffer.dispose();
  94781. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94782. }
  94783. if (this._indexBuffer) {
  94784. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94785. this._indexBuffer = null;
  94786. }
  94787. if (this.texture) {
  94788. this.texture.dispose();
  94789. this.texture = null;
  94790. }
  94791. // Remove from scene
  94792. var index = this._scene.layers.indexOf(this);
  94793. this._scene.layers.splice(index, 1);
  94794. // Callback
  94795. this.onDisposeObservable.notifyObservers(this);
  94796. this.onDisposeObservable.clear();
  94797. this.onAfterRenderObservable.clear();
  94798. this.onBeforeRenderObservable.clear();
  94799. };
  94800. return Layer;
  94801. }());
  94802. BABYLON.Layer = Layer;
  94803. })(BABYLON || (BABYLON = {}));
  94804. //# sourceMappingURL=babylon.layer.js.map
  94805. var BABYLON;
  94806. (function (BABYLON) {
  94807. var TextureTools = /** @class */ (function () {
  94808. function TextureTools() {
  94809. }
  94810. /**
  94811. * Uses the GPU to create a copy texture rescaled at a given size
  94812. * @param texture Texture to copy from
  94813. * @param width Desired width
  94814. * @param height Desired height
  94815. * @return Generated texture
  94816. */
  94817. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94818. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94819. var scene = texture.getScene();
  94820. var engine = scene.getEngine();
  94821. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94822. rtt.wrapU = texture.wrapU;
  94823. rtt.wrapV = texture.wrapV;
  94824. rtt.uOffset = texture.uOffset;
  94825. rtt.vOffset = texture.vOffset;
  94826. rtt.uScale = texture.uScale;
  94827. rtt.vScale = texture.vScale;
  94828. rtt.uAng = texture.uAng;
  94829. rtt.vAng = texture.vAng;
  94830. rtt.wAng = texture.wAng;
  94831. rtt.coordinatesIndex = texture.coordinatesIndex;
  94832. rtt.level = texture.level;
  94833. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94834. rtt._texture.isReady = false;
  94835. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94836. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94837. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94838. passPostProcess.getEffect().executeWhenCompiled(function () {
  94839. passPostProcess.onApply = function (effect) {
  94840. effect.setTexture("textureSampler", texture);
  94841. };
  94842. var internalTexture = rtt.getInternalTexture();
  94843. if (internalTexture) {
  94844. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94845. engine.unBindFramebuffer(internalTexture);
  94846. rtt.disposeFramebufferObjects();
  94847. passPostProcess.dispose();
  94848. internalTexture.isReady = true;
  94849. }
  94850. });
  94851. return rtt;
  94852. };
  94853. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94854. if (!scene._environmentBRDFTexture) {
  94855. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94856. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94857. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94858. scene._environmentBRDFTexture = texture;
  94859. }
  94860. return scene._environmentBRDFTexture;
  94861. };
  94862. 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=";
  94863. return TextureTools;
  94864. }());
  94865. BABYLON.TextureTools = TextureTools;
  94866. })(BABYLON || (BABYLON = {}));
  94867. //# sourceMappingURL=babylon.textureTools.js.map
  94868. var BABYLON;
  94869. (function (BABYLON) {
  94870. var FramingBehavior = /** @class */ (function () {
  94871. function FramingBehavior() {
  94872. this._mode = FramingBehavior.FitFrustumSidesMode;
  94873. this._radiusScale = 1.0;
  94874. this._positionScale = 0.5;
  94875. this._defaultElevation = 0.3;
  94876. this._elevationReturnTime = 1500;
  94877. this._elevationReturnWaitTime = 1000;
  94878. this._zoomStopsAnimation = false;
  94879. this._framingTime = 1500;
  94880. this._isPointerDown = false;
  94881. this._lastInteractionTime = -Infinity;
  94882. // Framing control
  94883. this._animatables = new Array();
  94884. this._betaIsAnimating = false;
  94885. }
  94886. Object.defineProperty(FramingBehavior.prototype, "name", {
  94887. get: function () {
  94888. return "Framing";
  94889. },
  94890. enumerable: true,
  94891. configurable: true
  94892. });
  94893. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94894. /**
  94895. * Gets current mode used by the behavior.
  94896. */
  94897. get: function () {
  94898. return this._mode;
  94899. },
  94900. /**
  94901. * Sets the current mode used by the behavior
  94902. */
  94903. set: function (mode) {
  94904. this._mode = mode;
  94905. },
  94906. enumerable: true,
  94907. configurable: true
  94908. });
  94909. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94910. /**
  94911. * Gets the scale applied to the radius
  94912. */
  94913. get: function () {
  94914. return this._radiusScale;
  94915. },
  94916. /**
  94917. * Sets the scale applied to the radius (1 by default)
  94918. */
  94919. set: function (radius) {
  94920. this._radiusScale = radius;
  94921. },
  94922. enumerable: true,
  94923. configurable: true
  94924. });
  94925. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94926. /**
  94927. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94928. */
  94929. get: function () {
  94930. return this._positionScale;
  94931. },
  94932. /**
  94933. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94934. */
  94935. set: function (scale) {
  94936. this._positionScale = scale;
  94937. },
  94938. enumerable: true,
  94939. configurable: true
  94940. });
  94941. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94942. /**
  94943. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94944. * behaviour is triggered, in radians.
  94945. */
  94946. get: function () {
  94947. return this._defaultElevation;
  94948. },
  94949. /**
  94950. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94951. * behaviour is triggered, in radians.
  94952. */
  94953. set: function (elevation) {
  94954. this._defaultElevation = elevation;
  94955. },
  94956. enumerable: true,
  94957. configurable: true
  94958. });
  94959. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94960. /**
  94961. * Gets the time (in milliseconds) taken to return to the default beta position.
  94962. * Negative value indicates camera should not return to default.
  94963. */
  94964. get: function () {
  94965. return this._elevationReturnTime;
  94966. },
  94967. /**
  94968. * Sets the time (in milliseconds) taken to return to the default beta position.
  94969. * Negative value indicates camera should not return to default.
  94970. */
  94971. set: function (speed) {
  94972. this._elevationReturnTime = speed;
  94973. },
  94974. enumerable: true,
  94975. configurable: true
  94976. });
  94977. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94978. /**
  94979. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94980. */
  94981. get: function () {
  94982. return this._elevationReturnWaitTime;
  94983. },
  94984. /**
  94985. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94986. */
  94987. set: function (time) {
  94988. this._elevationReturnWaitTime = time;
  94989. },
  94990. enumerable: true,
  94991. configurable: true
  94992. });
  94993. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94994. /**
  94995. * Gets the flag that indicates if user zooming should stop animation.
  94996. */
  94997. get: function () {
  94998. return this._zoomStopsAnimation;
  94999. },
  95000. /**
  95001. * Sets the flag that indicates if user zooming should stop animation.
  95002. */
  95003. set: function (flag) {
  95004. this._zoomStopsAnimation = flag;
  95005. },
  95006. enumerable: true,
  95007. configurable: true
  95008. });
  95009. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  95010. /**
  95011. * Gets the transition time when framing the mesh, in milliseconds
  95012. */
  95013. get: function () {
  95014. return this._framingTime;
  95015. },
  95016. /**
  95017. * Sets the transition time when framing the mesh, in milliseconds
  95018. */
  95019. set: function (time) {
  95020. this._framingTime = time;
  95021. },
  95022. enumerable: true,
  95023. configurable: true
  95024. });
  95025. FramingBehavior.prototype.init = function () {
  95026. // Do notihng
  95027. };
  95028. FramingBehavior.prototype.attach = function (camera) {
  95029. var _this = this;
  95030. this._attachedCamera = camera;
  95031. var scene = this._attachedCamera.getScene();
  95032. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  95033. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95034. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95035. _this._isPointerDown = true;
  95036. return;
  95037. }
  95038. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95039. _this._isPointerDown = false;
  95040. }
  95041. });
  95042. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95043. if (mesh) {
  95044. _this.zoomOnMesh(mesh);
  95045. }
  95046. });
  95047. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95048. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95049. _this._applyUserInteraction();
  95050. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  95051. // back to the default position after a given timeout
  95052. _this._maintainCameraAboveGround();
  95053. });
  95054. };
  95055. FramingBehavior.prototype.detach = function () {
  95056. if (!this._attachedCamera) {
  95057. return;
  95058. }
  95059. var scene = this._attachedCamera.getScene();
  95060. if (this._onPrePointerObservableObserver) {
  95061. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95062. }
  95063. if (this._onAfterCheckInputsObserver) {
  95064. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95065. }
  95066. if (this._onMeshTargetChangedObserver) {
  95067. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95068. }
  95069. this._attachedCamera = null;
  95070. };
  95071. /**
  95072. * Targets the given mesh and updates zoom level accordingly.
  95073. * @param mesh The mesh to target.
  95074. * @param radius Optional. If a cached radius position already exists, overrides default.
  95075. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95076. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95077. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95078. */
  95079. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95080. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95081. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95082. mesh.computeWorldMatrix(true);
  95083. var boundingBox = mesh.getBoundingInfo().boundingBox;
  95084. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  95085. };
  95086. /**
  95087. * Targets the given mesh with its children and updates zoom level accordingly.
  95088. * @param mesh The mesh to target.
  95089. * @param radius Optional. If a cached radius position already exists, overrides default.
  95090. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95091. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95092. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95093. */
  95094. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95095. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95096. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95097. mesh.computeWorldMatrix(true);
  95098. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  95099. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  95100. };
  95101. /**
  95102. * Targets the given meshes with their children and updates zoom level accordingly.
  95103. * @param meshes The mesh to target.
  95104. * @param radius Optional. If a cached radius position already exists, overrides default.
  95105. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95106. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95107. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95108. */
  95109. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  95110. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95111. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95112. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  95113. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  95114. for (var i = 0; i < meshes.length; i++) {
  95115. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  95116. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  95117. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  95118. }
  95119. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  95120. };
  95121. /**
  95122. * Targets the given mesh and updates zoom level accordingly.
  95123. * @param mesh The mesh to target.
  95124. * @param radius Optional. If a cached radius position already exists, overrides default.
  95125. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95126. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95127. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95128. */
  95129. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  95130. var _this = this;
  95131. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95132. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95133. var zoomTarget;
  95134. if (!this._attachedCamera) {
  95135. return;
  95136. }
  95137. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  95138. var bottom = minimumWorld.y;
  95139. var top = maximumWorld.y;
  95140. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  95141. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  95142. if (focusOnOriginXZ) {
  95143. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  95144. }
  95145. else {
  95146. var centerWorld = minimumWorld.add(radiusWorld);
  95147. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  95148. }
  95149. if (!this._vectorTransition) {
  95150. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  95151. }
  95152. this._betaIsAnimating = true;
  95153. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  95154. if (animatable) {
  95155. this._animatables.push(animatable);
  95156. }
  95157. // sets the radius and lower radius bounds
  95158. // Small delta ensures camera is not always at lower zoom limit.
  95159. var radius = 0;
  95160. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  95161. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95162. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  95163. radius = position;
  95164. }
  95165. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95166. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95167. if (this._attachedCamera.lowerRadiusLimit === null) {
  95168. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  95169. }
  95170. }
  95171. // Set sensibilities
  95172. var extend = maximumWorld.subtract(minimumWorld).length();
  95173. this._attachedCamera.panningSensibility = 5000 / extend;
  95174. this._attachedCamera.wheelPrecision = 100 / radius;
  95175. // transition to new radius
  95176. if (!this._radiusTransition) {
  95177. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95178. }
  95179. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  95180. _this.stopAllAnimations();
  95181. if (onAnimationEnd) {
  95182. onAnimationEnd();
  95183. }
  95184. if (_this._attachedCamera) {
  95185. _this._attachedCamera.storeState();
  95186. }
  95187. });
  95188. if (animatable) {
  95189. this._animatables.push(animatable);
  95190. }
  95191. };
  95192. /**
  95193. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  95194. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  95195. * frustum width.
  95196. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  95197. * to fully enclose the mesh in the viewing frustum.
  95198. */
  95199. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  95200. var size = maximumWorld.subtract(minimumWorld);
  95201. var boxVectorGlobalDiagonal = size.length();
  95202. var frustumSlope = this._getFrustumSlope();
  95203. // Formula for setting distance
  95204. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  95205. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  95206. // Horizon distance
  95207. var radius = radiusWithoutFraming * this._radiusScale;
  95208. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  95209. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  95210. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  95211. var camera = this._attachedCamera;
  95212. if (!camera) {
  95213. return 0;
  95214. }
  95215. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95216. // Don't exceed the requested limit
  95217. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  95218. }
  95219. // Don't exceed the upper radius limit
  95220. if (camera.upperRadiusLimit) {
  95221. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  95222. }
  95223. return distance;
  95224. };
  95225. /**
  95226. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  95227. * is automatically returned to its default position (expected to be above ground plane).
  95228. */
  95229. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  95230. var _this = this;
  95231. if (this._elevationReturnTime < 0) {
  95232. return;
  95233. }
  95234. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  95235. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  95236. var limitBeta = Math.PI * 0.5;
  95237. // Bring the camera back up if below the ground plane
  95238. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  95239. this._betaIsAnimating = true;
  95240. //Transition to new position
  95241. this.stopAllAnimations();
  95242. if (!this._betaTransition) {
  95243. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95244. }
  95245. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  95246. _this._clearAnimationLocks();
  95247. _this.stopAllAnimations();
  95248. });
  95249. if (animatabe) {
  95250. this._animatables.push(animatabe);
  95251. }
  95252. }
  95253. };
  95254. /**
  95255. * Returns the frustum slope based on the canvas ratio and camera FOV
  95256. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  95257. */
  95258. FramingBehavior.prototype._getFrustumSlope = function () {
  95259. // Calculate the viewport ratio
  95260. // Aspect Ratio is Height/Width.
  95261. var camera = this._attachedCamera;
  95262. if (!camera) {
  95263. return BABYLON.Vector2.Zero();
  95264. }
  95265. var engine = camera.getScene().getEngine();
  95266. var aspectRatio = engine.getAspectRatio(camera);
  95267. // Camera FOV is the vertical field of view (top-bottom) in radians.
  95268. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  95269. var frustumSlopeY = Math.tan(camera.fov / 2);
  95270. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  95271. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  95272. // along the forward vector.
  95273. var frustumSlopeX = frustumSlopeY * aspectRatio;
  95274. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  95275. };
  95276. /**
  95277. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  95278. */
  95279. FramingBehavior.prototype._clearAnimationLocks = function () {
  95280. this._betaIsAnimating = false;
  95281. };
  95282. /**
  95283. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95284. */
  95285. FramingBehavior.prototype._applyUserInteraction = function () {
  95286. if (this.isUserIsMoving) {
  95287. this._lastInteractionTime = BABYLON.Tools.Now;
  95288. this.stopAllAnimations();
  95289. this._clearAnimationLocks();
  95290. }
  95291. };
  95292. /**
  95293. * Stops and removes all animations that have been applied to the camera
  95294. */
  95295. FramingBehavior.prototype.stopAllAnimations = function () {
  95296. if (this._attachedCamera) {
  95297. this._attachedCamera.animations = [];
  95298. }
  95299. while (this._animatables.length) {
  95300. if (this._animatables[0]) {
  95301. this._animatables[0].onAnimationEnd = null;
  95302. this._animatables[0].stop();
  95303. }
  95304. this._animatables.shift();
  95305. }
  95306. };
  95307. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  95308. /**
  95309. * Gets a value indicating if the user is moving the camera
  95310. */
  95311. get: function () {
  95312. if (!this._attachedCamera) {
  95313. return false;
  95314. }
  95315. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95316. this._attachedCamera.inertialBetaOffset !== 0 ||
  95317. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95318. this._attachedCamera.inertialPanningX !== 0 ||
  95319. this._attachedCamera.inertialPanningY !== 0 ||
  95320. this._isPointerDown;
  95321. },
  95322. enumerable: true,
  95323. configurable: true
  95324. });
  95325. /**
  95326. * The easing function used by animations
  95327. */
  95328. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  95329. /**
  95330. * The easing mode used by animations
  95331. */
  95332. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  95333. // Statics
  95334. /**
  95335. * The camera can move all the way towards the mesh.
  95336. */
  95337. FramingBehavior.IgnoreBoundsSizeMode = 0;
  95338. /**
  95339. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  95340. */
  95341. FramingBehavior.FitFrustumSidesMode = 1;
  95342. return FramingBehavior;
  95343. }());
  95344. BABYLON.FramingBehavior = FramingBehavior;
  95345. })(BABYLON || (BABYLON = {}));
  95346. //# sourceMappingURL=babylon.framingBehavior.js.map
  95347. var BABYLON;
  95348. (function (BABYLON) {
  95349. /**
  95350. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  95351. */
  95352. var BouncingBehavior = /** @class */ (function () {
  95353. function BouncingBehavior() {
  95354. /**
  95355. * The duration of the animation, in milliseconds
  95356. */
  95357. this.transitionDuration = 450;
  95358. /**
  95359. * Length of the distance animated by the transition when lower radius is reached
  95360. */
  95361. this.lowerRadiusTransitionRange = 2;
  95362. /**
  95363. * Length of the distance animated by the transition when upper radius is reached
  95364. */
  95365. this.upperRadiusTransitionRange = -2;
  95366. this._autoTransitionRange = false;
  95367. // Animations
  95368. this._radiusIsAnimating = false;
  95369. this._radiusBounceTransition = null;
  95370. this._animatables = new Array();
  95371. }
  95372. Object.defineProperty(BouncingBehavior.prototype, "name", {
  95373. get: function () {
  95374. return "Bouncing";
  95375. },
  95376. enumerable: true,
  95377. configurable: true
  95378. });
  95379. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  95380. /**
  95381. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95382. */
  95383. get: function () {
  95384. return this._autoTransitionRange;
  95385. },
  95386. /**
  95387. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95388. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  95389. */
  95390. set: function (value) {
  95391. var _this = this;
  95392. if (this._autoTransitionRange === value) {
  95393. return;
  95394. }
  95395. this._autoTransitionRange = value;
  95396. var camera = this._attachedCamera;
  95397. if (!camera) {
  95398. return;
  95399. }
  95400. if (value) {
  95401. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95402. if (!mesh) {
  95403. return;
  95404. }
  95405. mesh.computeWorldMatrix(true);
  95406. var diagonal = mesh.getBoundingInfo().diagonalLength;
  95407. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  95408. _this.upperRadiusTransitionRange = diagonal * 0.05;
  95409. });
  95410. }
  95411. else if (this._onMeshTargetChangedObserver) {
  95412. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95413. }
  95414. },
  95415. enumerable: true,
  95416. configurable: true
  95417. });
  95418. BouncingBehavior.prototype.init = function () {
  95419. // Do notihng
  95420. };
  95421. BouncingBehavior.prototype.attach = function (camera) {
  95422. var _this = this;
  95423. this._attachedCamera = camera;
  95424. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95425. if (!_this._attachedCamera) {
  95426. return;
  95427. }
  95428. // Add the bounce animation to the lower radius limit
  95429. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  95430. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  95431. }
  95432. // Add the bounce animation to the upper radius limit
  95433. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  95434. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  95435. }
  95436. });
  95437. };
  95438. BouncingBehavior.prototype.detach = function () {
  95439. if (!this._attachedCamera) {
  95440. return;
  95441. }
  95442. if (this._onAfterCheckInputsObserver) {
  95443. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95444. }
  95445. if (this._onMeshTargetChangedObserver) {
  95446. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95447. }
  95448. this._attachedCamera = null;
  95449. };
  95450. /**
  95451. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  95452. * @param radiusLimit The limit to check against.
  95453. * @return Bool to indicate if at limit.
  95454. */
  95455. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  95456. if (!this._attachedCamera) {
  95457. return false;
  95458. }
  95459. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  95460. return true;
  95461. }
  95462. return false;
  95463. };
  95464. /**
  95465. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  95466. * @param radiusDelta The delta by which to animate to. Can be negative.
  95467. */
  95468. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  95469. var _this = this;
  95470. if (!this._attachedCamera) {
  95471. return;
  95472. }
  95473. if (!this._radiusBounceTransition) {
  95474. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  95475. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  95476. }
  95477. // Prevent zoom until bounce has completed
  95478. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  95479. this._attachedCamera.wheelPrecision = Infinity;
  95480. this._attachedCamera.inertialRadiusOffset = 0;
  95481. // Animate to the radius limit
  95482. this.stopAllAnimations();
  95483. this._radiusIsAnimating = true;
  95484. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  95485. if (animatable) {
  95486. this._animatables.push(animatable);
  95487. }
  95488. };
  95489. /**
  95490. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  95491. */
  95492. BouncingBehavior.prototype._clearAnimationLocks = function () {
  95493. this._radiusIsAnimating = false;
  95494. if (this._attachedCamera) {
  95495. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  95496. }
  95497. };
  95498. /**
  95499. * Stops and removes all animations that have been applied to the camera
  95500. */
  95501. BouncingBehavior.prototype.stopAllAnimations = function () {
  95502. if (this._attachedCamera) {
  95503. this._attachedCamera.animations = [];
  95504. }
  95505. while (this._animatables.length) {
  95506. this._animatables[0].onAnimationEnd = null;
  95507. this._animatables[0].stop();
  95508. this._animatables.shift();
  95509. }
  95510. };
  95511. /**
  95512. * The easing function used by animations
  95513. */
  95514. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  95515. /**
  95516. * The easing mode used by animations
  95517. */
  95518. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  95519. return BouncingBehavior;
  95520. }());
  95521. BABYLON.BouncingBehavior = BouncingBehavior;
  95522. })(BABYLON || (BABYLON = {}));
  95523. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  95524. var BABYLON;
  95525. (function (BABYLON) {
  95526. var AutoRotationBehavior = /** @class */ (function () {
  95527. function AutoRotationBehavior() {
  95528. this._zoomStopsAnimation = false;
  95529. this._idleRotationSpeed = 0.05;
  95530. this._idleRotationWaitTime = 2000;
  95531. this._idleRotationSpinupTime = 2000;
  95532. this._isPointerDown = false;
  95533. this._lastFrameTime = null;
  95534. this._lastInteractionTime = -Infinity;
  95535. this._cameraRotationSpeed = 0;
  95536. this._lastFrameRadius = 0;
  95537. }
  95538. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95539. get: function () {
  95540. return "AutoRotation";
  95541. },
  95542. enumerable: true,
  95543. configurable: true
  95544. });
  95545. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95546. /**
  95547. * Gets the flag that indicates if user zooming should stop animation.
  95548. */
  95549. get: function () {
  95550. return this._zoomStopsAnimation;
  95551. },
  95552. /**
  95553. * Sets the flag that indicates if user zooming should stop animation.
  95554. */
  95555. set: function (flag) {
  95556. this._zoomStopsAnimation = flag;
  95557. },
  95558. enumerable: true,
  95559. configurable: true
  95560. });
  95561. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95562. /**
  95563. * Gets the default speed at which the camera rotates around the model.
  95564. */
  95565. get: function () {
  95566. return this._idleRotationSpeed;
  95567. },
  95568. /**
  95569. * Sets the default speed at which the camera rotates around the model.
  95570. */
  95571. set: function (speed) {
  95572. this._idleRotationSpeed = speed;
  95573. },
  95574. enumerable: true,
  95575. configurable: true
  95576. });
  95577. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95578. /**
  95579. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95580. */
  95581. get: function () {
  95582. return this._idleRotationWaitTime;
  95583. },
  95584. /**
  95585. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95586. */
  95587. set: function (time) {
  95588. this._idleRotationWaitTime = time;
  95589. },
  95590. enumerable: true,
  95591. configurable: true
  95592. });
  95593. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95594. /**
  95595. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95596. */
  95597. get: function () {
  95598. return this._idleRotationSpinupTime;
  95599. },
  95600. /**
  95601. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95602. */
  95603. set: function (time) {
  95604. this._idleRotationSpinupTime = time;
  95605. },
  95606. enumerable: true,
  95607. configurable: true
  95608. });
  95609. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95610. /**
  95611. * Gets a value indicating if the camera is currently rotating because of this behavior
  95612. */
  95613. get: function () {
  95614. return Math.abs(this._cameraRotationSpeed) > 0;
  95615. },
  95616. enumerable: true,
  95617. configurable: true
  95618. });
  95619. AutoRotationBehavior.prototype.init = function () {
  95620. // Do notihng
  95621. };
  95622. AutoRotationBehavior.prototype.attach = function (camera) {
  95623. var _this = this;
  95624. this._attachedCamera = camera;
  95625. var scene = this._attachedCamera.getScene();
  95626. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95627. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95628. _this._isPointerDown = true;
  95629. return;
  95630. }
  95631. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95632. _this._isPointerDown = false;
  95633. }
  95634. });
  95635. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95636. var now = BABYLON.Tools.Now;
  95637. var dt = 0;
  95638. if (_this._lastFrameTime != null) {
  95639. dt = now - _this._lastFrameTime;
  95640. }
  95641. _this._lastFrameTime = now;
  95642. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95643. _this._applyUserInteraction();
  95644. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95645. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95646. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95647. // Step camera rotation by rotation speed
  95648. if (_this._attachedCamera) {
  95649. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95650. }
  95651. });
  95652. };
  95653. AutoRotationBehavior.prototype.detach = function () {
  95654. if (!this._attachedCamera) {
  95655. return;
  95656. }
  95657. var scene = this._attachedCamera.getScene();
  95658. if (this._onPrePointerObservableObserver) {
  95659. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95660. }
  95661. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95662. this._attachedCamera = null;
  95663. };
  95664. /**
  95665. * Returns true if user is scrolling.
  95666. * @return true if user is scrolling.
  95667. */
  95668. AutoRotationBehavior.prototype._userIsZooming = function () {
  95669. if (!this._attachedCamera) {
  95670. return false;
  95671. }
  95672. return this._attachedCamera.inertialRadiusOffset !== 0;
  95673. };
  95674. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95675. if (!this._attachedCamera) {
  95676. return false;
  95677. }
  95678. var zoomHasHitLimit = false;
  95679. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95680. zoomHasHitLimit = true;
  95681. }
  95682. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95683. this._lastFrameRadius = this._attachedCamera.radius;
  95684. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95685. };
  95686. /**
  95687. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95688. */
  95689. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95690. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95691. this._lastInteractionTime = BABYLON.Tools.Now;
  95692. }
  95693. };
  95694. // Tools
  95695. AutoRotationBehavior.prototype._userIsMoving = function () {
  95696. if (!this._attachedCamera) {
  95697. return false;
  95698. }
  95699. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95700. this._attachedCamera.inertialBetaOffset !== 0 ||
  95701. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95702. this._attachedCamera.inertialPanningX !== 0 ||
  95703. this._attachedCamera.inertialPanningY !== 0 ||
  95704. this._isPointerDown;
  95705. };
  95706. return AutoRotationBehavior;
  95707. }());
  95708. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95709. })(BABYLON || (BABYLON = {}));
  95710. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95711. var BABYLON;
  95712. (function (BABYLON) {
  95713. /**
  95714. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  95715. */
  95716. var PointerDragBehavior = /** @class */ (function () {
  95717. /**
  95718. * Creates a pointer drag behavior that can be attached to a mesh
  95719. * @param options The drag axis or normal of the plane that will be dragged across. pointerObservableScene can be used to listen to drag events from another scene(eg. if the attached mesh is in an overlay scene).
  95720. */
  95721. function PointerDragBehavior(options) {
  95722. this.options = options;
  95723. this._draggingID = -1;
  95724. /**
  95725. * Fires each time the attached mesh is dragged with the pointer
  95726. */
  95727. this.onDragObservable = new BABYLON.Observable();
  95728. /**
  95729. * Fires each time a drag begins (eg. mouse down on mesh)
  95730. */
  95731. this.onDragStartObservable = new BABYLON.Observable();
  95732. /**
  95733. * Fires each time a drag ends (eg. mouse release after drag)
  95734. */
  95735. this.onDragEndObservable = new BABYLON.Observable();
  95736. /**
  95737. * If the attached mesh should be moved when dragged
  95738. */
  95739. this.moveAttached = true;
  95740. /**
  95741. * Mesh with the position where the drag plane should be placed
  95742. */
  95743. this._dragPlaneParent = null;
  95744. var optionCount = 0;
  95745. if (options.dragAxis) {
  95746. optionCount++;
  95747. }
  95748. if (options.dragPlaneNormal) {
  95749. optionCount++;
  95750. }
  95751. if (optionCount > 1) {
  95752. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  95753. }
  95754. if (optionCount < 1) {
  95755. throw "At least one drag mode option must be specified";
  95756. }
  95757. }
  95758. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  95759. /**
  95760. * The name of the behavior
  95761. */
  95762. get: function () {
  95763. return "PointerDrag";
  95764. },
  95765. enumerable: true,
  95766. configurable: true
  95767. });
  95768. /**
  95769. * Initializes the behavior
  95770. */
  95771. PointerDragBehavior.prototype.init = function () { };
  95772. /**
  95773. * Attaches the drag behavior the passed in mesh
  95774. * @param ownerNode The mesh that will be dragged around once attached
  95775. */
  95776. PointerDragBehavior.prototype.attach = function (ownerNode) {
  95777. var _this = this;
  95778. this._scene = ownerNode.getScene();
  95779. if (!this.options.pointerObservableScene) {
  95780. this.options.pointerObservableScene = this._scene;
  95781. }
  95782. this._attachedNode = ownerNode;
  95783. // Initialize drag plane to not interfere with existing scene
  95784. if (!PointerDragBehavior._planeScene) {
  95785. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  95786. this._scene.getEngine().scenes.pop();
  95787. }
  95788. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  95789. // State of the drag
  95790. var dragging = false;
  95791. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  95792. var delta = new BABYLON.Vector3(0, 0, 0);
  95793. var pickPredicate = function (m) {
  95794. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  95795. };
  95796. this._pointerObserver = this.options.pointerObservableScene.onPrePointerObservable.add(function (pointerInfoPre, eventState) {
  95797. // Check if attached mesh is picked
  95798. var pickInfo = pointerInfoPre.ray ? _this._scene.pickWithRay(pointerInfoPre.ray, pickPredicate) : _this._scene.pick(_this._scene.pointerX, _this._scene.pointerY, pickPredicate);
  95799. if (pickInfo) {
  95800. pickInfo.ray = pointerInfoPre.ray;
  95801. if (!pickInfo.ray) {
  95802. pickInfo.ray = _this.options.pointerObservableScene.createPickingRay(_this._scene.pointerX, _this._scene.pointerY, BABYLON.Matrix.Identity(), _this._scene.activeCamera);
  95803. }
  95804. if (pickInfo.hit) {
  95805. eventState.skipNextObservers = true;
  95806. }
  95807. }
  95808. if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95809. if (!dragging && pickInfo && pickInfo.hit && pickInfo.pickedMesh && pickInfo.ray) {
  95810. _this._updateDragPlanePosition(pickInfo.ray);
  95811. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  95812. if (pickedPoint) {
  95813. dragging = true;
  95814. _this._draggingID = pointerInfoPre.event.pointerId;
  95815. lastPosition.copyFrom(pickedPoint);
  95816. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  95817. }
  95818. }
  95819. }
  95820. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERUP) {
  95821. if (_this._draggingID == pointerInfoPre.event.pointerId) {
  95822. dragging = false;
  95823. _this._draggingID = -1;
  95824. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  95825. }
  95826. }
  95827. else if (pointerInfoPre.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95828. if (_this._draggingID == pointerInfoPre.event.pointerId && dragging && pickInfo && pickInfo.ray) {
  95829. var pickedPoint = _this._pickWithRayOnDragPlane(pickInfo.ray);
  95830. _this._updateDragPlanePosition(pickInfo.ray);
  95831. if (pickedPoint) {
  95832. // depending on the drag mode option drag accordingly
  95833. if (_this.options.dragAxis) {
  95834. //get the closest point on the dragaxis from the selected mesh to the picked point location
  95835. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  95836. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  95837. }
  95838. else {
  95839. pickedPoint.subtractToRef(lastPosition, delta);
  95840. }
  95841. if (_this.moveAttached) {
  95842. _this._attachedNode.position.addInPlace(delta);
  95843. }
  95844. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  95845. lastPosition.copyFrom(pickedPoint);
  95846. }
  95847. }
  95848. }
  95849. });
  95850. };
  95851. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  95852. var _this = this;
  95853. if (!ray) {
  95854. return null;
  95855. }
  95856. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  95857. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  95858. return pickResult.pickedPoint;
  95859. }
  95860. else {
  95861. return null;
  95862. }
  95863. };
  95864. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  95865. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  95866. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  95867. if (this.options.dragAxis) {
  95868. var camPos = ray.origin;
  95869. // Calculate plane normal in direction of camera but perpendicular to drag axis
  95870. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  95871. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  95872. // Get perpendicular line from direction to camera and drag axis
  95873. var lineA = pointB.subtract(pointA);
  95874. var lineB = pointC.subtract(pointA);
  95875. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  95876. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  95877. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  95878. this._dragPlane.position.copyFrom(pointA);
  95879. this._dragPlane.lookAt(pointA.add(norm));
  95880. }
  95881. else if (this.options.dragPlaneNormal) {
  95882. this._dragPlane.position.copyFrom(pointA);
  95883. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  95884. }
  95885. this._dragPlane.computeWorldMatrix(true);
  95886. };
  95887. /**
  95888. * Detaches the behavior from the mesh
  95889. */
  95890. PointerDragBehavior.prototype.detach = function () {
  95891. if (this._pointerObserver) {
  95892. this._scene.onPrePointerObservable.remove(this._pointerObserver);
  95893. }
  95894. };
  95895. return PointerDragBehavior;
  95896. }());
  95897. BABYLON.PointerDragBehavior = PointerDragBehavior;
  95898. })(BABYLON || (BABYLON = {}));
  95899. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  95900. var BABYLON;
  95901. (function (BABYLON) {
  95902. var NullEngineOptions = /** @class */ (function () {
  95903. function NullEngineOptions() {
  95904. this.renderWidth = 512;
  95905. this.renderHeight = 256;
  95906. this.textureSize = 512;
  95907. this.deterministicLockstep = false;
  95908. this.lockstepMaxSteps = 4;
  95909. }
  95910. return NullEngineOptions;
  95911. }());
  95912. BABYLON.NullEngineOptions = NullEngineOptions;
  95913. /**
  95914. * The null engine class provides support for headless version of babylon.js.
  95915. * This can be used in server side scenario or for testing purposes
  95916. */
  95917. var NullEngine = /** @class */ (function (_super) {
  95918. __extends(NullEngine, _super);
  95919. function NullEngine(options) {
  95920. if (options === void 0) { options = new NullEngineOptions(); }
  95921. var _this = _super.call(this, null) || this;
  95922. if (options.deterministicLockstep === undefined) {
  95923. options.deterministicLockstep = false;
  95924. }
  95925. if (options.lockstepMaxSteps === undefined) {
  95926. options.lockstepMaxSteps = 4;
  95927. }
  95928. _this._options = options;
  95929. // Init caps
  95930. // We consider we are on a webgl1 capable device
  95931. _this._caps = new BABYLON.EngineCapabilities();
  95932. _this._caps.maxTexturesImageUnits = 16;
  95933. _this._caps.maxVertexTextureImageUnits = 16;
  95934. _this._caps.maxTextureSize = 512;
  95935. _this._caps.maxCubemapTextureSize = 512;
  95936. _this._caps.maxRenderTextureSize = 512;
  95937. _this._caps.maxVertexAttribs = 16;
  95938. _this._caps.maxVaryingVectors = 16;
  95939. _this._caps.maxFragmentUniformVectors = 16;
  95940. _this._caps.maxVertexUniformVectors = 16;
  95941. // Extensions
  95942. _this._caps.standardDerivatives = false;
  95943. _this._caps.astc = null;
  95944. _this._caps.s3tc = null;
  95945. _this._caps.pvrtc = null;
  95946. _this._caps.etc1 = null;
  95947. _this._caps.etc2 = null;
  95948. _this._caps.textureAnisotropicFilterExtension = null;
  95949. _this._caps.maxAnisotropy = 0;
  95950. _this._caps.uintIndices = false;
  95951. _this._caps.fragmentDepthSupported = false;
  95952. _this._caps.highPrecisionShaderSupported = true;
  95953. _this._caps.colorBufferFloat = false;
  95954. _this._caps.textureFloat = false;
  95955. _this._caps.textureFloatLinearFiltering = false;
  95956. _this._caps.textureFloatRender = false;
  95957. _this._caps.textureHalfFloat = false;
  95958. _this._caps.textureHalfFloatLinearFiltering = false;
  95959. _this._caps.textureHalfFloatRender = false;
  95960. _this._caps.textureLOD = false;
  95961. _this._caps.drawBuffersExtension = false;
  95962. _this._caps.depthTextureExtension = false;
  95963. _this._caps.vertexArrayObject = false;
  95964. _this._caps.instancedArrays = false;
  95965. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95966. // Wrappers
  95967. if (typeof URL === "undefined") {
  95968. URL = {
  95969. createObjectURL: function () { },
  95970. revokeObjectURL: function () { }
  95971. };
  95972. }
  95973. if (typeof Blob === "undefined") {
  95974. Blob = function () { };
  95975. }
  95976. return _this;
  95977. }
  95978. NullEngine.prototype.isDeterministicLockStep = function () {
  95979. return this._options.deterministicLockstep;
  95980. };
  95981. NullEngine.prototype.getLockstepMaxSteps = function () {
  95982. return this._options.lockstepMaxSteps;
  95983. };
  95984. NullEngine.prototype.getHardwareScalingLevel = function () {
  95985. return 1.0;
  95986. };
  95987. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95988. return {
  95989. capacity: 0,
  95990. references: 1,
  95991. is32Bits: false
  95992. };
  95993. };
  95994. NullEngine.prototype.createIndexBuffer = function (indices) {
  95995. return {
  95996. capacity: 0,
  95997. references: 1,
  95998. is32Bits: false
  95999. };
  96000. };
  96001. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  96002. if (stencil === void 0) { stencil = false; }
  96003. };
  96004. NullEngine.prototype.getRenderWidth = function (useScreen) {
  96005. if (useScreen === void 0) { useScreen = false; }
  96006. if (!useScreen && this._currentRenderTarget) {
  96007. return this._currentRenderTarget.width;
  96008. }
  96009. return this._options.renderWidth;
  96010. };
  96011. NullEngine.prototype.getRenderHeight = function (useScreen) {
  96012. if (useScreen === void 0) { useScreen = false; }
  96013. if (!useScreen && this._currentRenderTarget) {
  96014. return this._currentRenderTarget.height;
  96015. }
  96016. return this._options.renderHeight;
  96017. };
  96018. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  96019. this._cachedViewport = viewport;
  96020. };
  96021. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  96022. return {
  96023. transformFeedback: null,
  96024. __SPECTOR_rebuildProgram: null
  96025. };
  96026. };
  96027. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  96028. return [];
  96029. };
  96030. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  96031. return [];
  96032. };
  96033. NullEngine.prototype.bindSamplers = function (effect) {
  96034. this._currentEffect = null;
  96035. };
  96036. NullEngine.prototype.enableEffect = function (effect) {
  96037. this._currentEffect = effect;
  96038. if (effect.onBind) {
  96039. effect.onBind(effect);
  96040. }
  96041. effect.onBindObservable.notifyObservers(effect);
  96042. };
  96043. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  96044. if (zOffset === void 0) { zOffset = 0; }
  96045. if (reverseSide === void 0) { reverseSide = false; }
  96046. };
  96047. NullEngine.prototype.setIntArray = function (uniform, array) {
  96048. };
  96049. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  96050. };
  96051. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  96052. };
  96053. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  96054. };
  96055. NullEngine.prototype.setFloatArray = function (uniform, array) {
  96056. };
  96057. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  96058. };
  96059. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  96060. };
  96061. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  96062. };
  96063. NullEngine.prototype.setArray = function (uniform, array) {
  96064. };
  96065. NullEngine.prototype.setArray2 = function (uniform, array) {
  96066. };
  96067. NullEngine.prototype.setArray3 = function (uniform, array) {
  96068. };
  96069. NullEngine.prototype.setArray4 = function (uniform, array) {
  96070. };
  96071. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  96072. };
  96073. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  96074. };
  96075. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  96076. };
  96077. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  96078. };
  96079. NullEngine.prototype.setFloat = function (uniform, value) {
  96080. };
  96081. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  96082. };
  96083. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  96084. };
  96085. NullEngine.prototype.setBool = function (uniform, bool) {
  96086. };
  96087. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  96088. };
  96089. NullEngine.prototype.setColor3 = function (uniform, color3) {
  96090. };
  96091. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  96092. };
  96093. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  96094. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  96095. if (this._alphaMode === mode) {
  96096. return;
  96097. }
  96098. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  96099. if (!noDepthWriteChange) {
  96100. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  96101. }
  96102. this._alphaMode = mode;
  96103. };
  96104. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  96105. };
  96106. NullEngine.prototype.wipeCaches = function (bruteForce) {
  96107. if (this.preventCacheWipeBetweenFrames) {
  96108. return;
  96109. }
  96110. this.resetTextureCache();
  96111. this._currentEffect = null;
  96112. if (bruteForce) {
  96113. this._currentProgram = null;
  96114. this._stencilState.reset();
  96115. this._depthCullingState.reset();
  96116. this._alphaState.reset();
  96117. }
  96118. this._cachedVertexBuffers = null;
  96119. this._cachedIndexBuffer = null;
  96120. this._cachedEffectForVertexBuffers = null;
  96121. };
  96122. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  96123. };
  96124. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  96125. };
  96126. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  96127. };
  96128. NullEngine.prototype._createTexture = function () {
  96129. return {};
  96130. };
  96131. NullEngine.prototype._releaseTexture = function (texture) {
  96132. };
  96133. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  96134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96135. if (onLoad === void 0) { onLoad = null; }
  96136. if (onError === void 0) { onError = null; }
  96137. if (buffer === void 0) { buffer = null; }
  96138. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  96139. var url = String(urlArg);
  96140. texture.url = url;
  96141. texture.generateMipMaps = !noMipmap;
  96142. texture.samplingMode = samplingMode;
  96143. texture.invertY = invertY;
  96144. texture.baseWidth = this._options.textureSize;
  96145. texture.baseHeight = this._options.textureSize;
  96146. texture.width = this._options.textureSize;
  96147. texture.height = this._options.textureSize;
  96148. if (format) {
  96149. texture.format = format;
  96150. }
  96151. texture.isReady = true;
  96152. if (onLoad) {
  96153. onLoad();
  96154. }
  96155. this._internalTexturesCache.push(texture);
  96156. return texture;
  96157. };
  96158. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  96159. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  96160. if (options !== undefined && typeof options === "object") {
  96161. fullOptions.generateMipMaps = options.generateMipMaps;
  96162. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  96163. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  96164. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  96165. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  96166. }
  96167. else {
  96168. fullOptions.generateMipMaps = options;
  96169. fullOptions.generateDepthBuffer = true;
  96170. fullOptions.generateStencilBuffer = false;
  96171. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96172. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  96173. }
  96174. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  96175. var width = size.width || size;
  96176. var height = size.height || size;
  96177. texture._depthStencilBuffer = {};
  96178. texture._framebuffer = {};
  96179. texture.baseWidth = width;
  96180. texture.baseHeight = height;
  96181. texture.width = width;
  96182. texture.height = height;
  96183. texture.isReady = true;
  96184. texture.samples = 1;
  96185. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  96186. texture.samplingMode = fullOptions.samplingMode;
  96187. texture.type = fullOptions.type;
  96188. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  96189. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  96190. this._internalTexturesCache.push(texture);
  96191. return texture;
  96192. };
  96193. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  96194. texture.samplingMode = samplingMode;
  96195. };
  96196. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  96197. if (this._currentRenderTarget) {
  96198. this.unBindFramebuffer(this._currentRenderTarget);
  96199. }
  96200. this._currentRenderTarget = texture;
  96201. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  96202. if (this._cachedViewport && !forceFullscreenViewport) {
  96203. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  96204. }
  96205. };
  96206. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  96207. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  96208. this._currentRenderTarget = null;
  96209. if (onBeforeUnbind) {
  96210. if (texture._MSAAFramebuffer) {
  96211. this._currentFramebuffer = texture._framebuffer;
  96212. }
  96213. onBeforeUnbind();
  96214. }
  96215. this._currentFramebuffer = null;
  96216. };
  96217. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  96218. var vbo = {
  96219. capacity: 1,
  96220. references: 1,
  96221. is32Bits: false
  96222. };
  96223. return vbo;
  96224. };
  96225. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  96226. if (offset === void 0) { offset = 0; }
  96227. };
  96228. /**
  96229. * Updates a dynamic vertex buffer.
  96230. * @param vertexBuffer the vertex buffer to update
  96231. * @param data the data used to update the vertex buffer
  96232. * @param byteOffset the byte offset of the data (optional)
  96233. * @param byteLength the byte length of the data (optional)
  96234. */
  96235. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  96236. };
  96237. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  96238. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  96239. this._boundTexturesCache[this._activeChannel] = texture;
  96240. }
  96241. };
  96242. NullEngine.prototype._bindTexture = function (channel, texture) {
  96243. if (channel < 0) {
  96244. return;
  96245. }
  96246. this._bindTextureDirectly(0, texture);
  96247. };
  96248. NullEngine.prototype._releaseBuffer = function (buffer) {
  96249. buffer.references--;
  96250. if (buffer.references === 0) {
  96251. return true;
  96252. }
  96253. return false;
  96254. };
  96255. NullEngine.prototype.releaseEffects = function () {
  96256. };
  96257. return NullEngine;
  96258. }(BABYLON.Engine));
  96259. BABYLON.NullEngine = NullEngine;
  96260. })(BABYLON || (BABYLON = {}));
  96261. //# sourceMappingURL=babylon.nullEngine.js.map
  96262. var BABYLON;
  96263. (function (BABYLON) {
  96264. /**
  96265. * This class can be used to get instrumentation data from a Babylon engine
  96266. */
  96267. var EngineInstrumentation = /** @class */ (function () {
  96268. function EngineInstrumentation(engine) {
  96269. this.engine = engine;
  96270. this._captureGPUFrameTime = false;
  96271. this._gpuFrameTime = new BABYLON.PerfCounter();
  96272. this._captureShaderCompilationTime = false;
  96273. this._shaderCompilationTime = new BABYLON.PerfCounter();
  96274. // Observers
  96275. this._onBeginFrameObserver = null;
  96276. this._onEndFrameObserver = null;
  96277. this._onBeforeShaderCompilationObserver = null;
  96278. this._onAfterShaderCompilationObserver = null;
  96279. }
  96280. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  96281. // Properties
  96282. /**
  96283. * Gets the perf counter used for GPU frame time
  96284. */
  96285. get: function () {
  96286. return this._gpuFrameTime;
  96287. },
  96288. enumerable: true,
  96289. configurable: true
  96290. });
  96291. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  96292. /**
  96293. * Gets the GPU frame time capture status
  96294. */
  96295. get: function () {
  96296. return this._captureGPUFrameTime;
  96297. },
  96298. /**
  96299. * Enable or disable the GPU frame time capture
  96300. */
  96301. set: function (value) {
  96302. var _this = this;
  96303. if (value === this._captureGPUFrameTime) {
  96304. return;
  96305. }
  96306. this._captureGPUFrameTime = value;
  96307. if (value) {
  96308. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  96309. if (!_this._gpuFrameTimeToken) {
  96310. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  96311. }
  96312. });
  96313. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  96314. if (!_this._gpuFrameTimeToken) {
  96315. return;
  96316. }
  96317. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  96318. if (time > -1) {
  96319. _this._gpuFrameTimeToken = null;
  96320. _this._gpuFrameTime.fetchNewFrame();
  96321. _this._gpuFrameTime.addCount(time, true);
  96322. }
  96323. });
  96324. }
  96325. else {
  96326. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96327. this._onBeginFrameObserver = null;
  96328. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96329. this._onEndFrameObserver = null;
  96330. }
  96331. },
  96332. enumerable: true,
  96333. configurable: true
  96334. });
  96335. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  96336. /**
  96337. * Gets the perf counter used for shader compilation time
  96338. */
  96339. get: function () {
  96340. return this._shaderCompilationTime;
  96341. },
  96342. enumerable: true,
  96343. configurable: true
  96344. });
  96345. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  96346. /**
  96347. * Gets the shader compilation time capture status
  96348. */
  96349. get: function () {
  96350. return this._captureShaderCompilationTime;
  96351. },
  96352. /**
  96353. * Enable or disable the shader compilation time capture
  96354. */
  96355. set: function (value) {
  96356. var _this = this;
  96357. if (value === this._captureShaderCompilationTime) {
  96358. return;
  96359. }
  96360. this._captureShaderCompilationTime = value;
  96361. if (value) {
  96362. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  96363. _this._shaderCompilationTime.fetchNewFrame();
  96364. _this._shaderCompilationTime.beginMonitoring();
  96365. });
  96366. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  96367. _this._shaderCompilationTime.endMonitoring();
  96368. });
  96369. }
  96370. else {
  96371. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96372. this._onBeforeShaderCompilationObserver = null;
  96373. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96374. this._onAfterShaderCompilationObserver = null;
  96375. }
  96376. },
  96377. enumerable: true,
  96378. configurable: true
  96379. });
  96380. EngineInstrumentation.prototype.dispose = function () {
  96381. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96382. this._onBeginFrameObserver = null;
  96383. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96384. this._onEndFrameObserver = null;
  96385. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  96386. this._onBeforeShaderCompilationObserver = null;
  96387. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  96388. this._onAfterShaderCompilationObserver = null;
  96389. this.engine = null;
  96390. };
  96391. return EngineInstrumentation;
  96392. }());
  96393. BABYLON.EngineInstrumentation = EngineInstrumentation;
  96394. })(BABYLON || (BABYLON = {}));
  96395. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  96396. var BABYLON;
  96397. (function (BABYLON) {
  96398. /**
  96399. * This class can be used to get instrumentation data from a Babylon engine
  96400. */
  96401. var SceneInstrumentation = /** @class */ (function () {
  96402. function SceneInstrumentation(scene) {
  96403. var _this = this;
  96404. this.scene = scene;
  96405. this._captureActiveMeshesEvaluationTime = false;
  96406. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  96407. this._captureRenderTargetsRenderTime = false;
  96408. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  96409. this._captureFrameTime = false;
  96410. this._frameTime = new BABYLON.PerfCounter();
  96411. this._captureRenderTime = false;
  96412. this._renderTime = new BABYLON.PerfCounter();
  96413. this._captureInterFrameTime = false;
  96414. this._interFrameTime = new BABYLON.PerfCounter();
  96415. this._captureParticlesRenderTime = false;
  96416. this._particlesRenderTime = new BABYLON.PerfCounter();
  96417. this._captureSpritesRenderTime = false;
  96418. this._spritesRenderTime = new BABYLON.PerfCounter();
  96419. this._capturePhysicsTime = false;
  96420. this._physicsTime = new BABYLON.PerfCounter();
  96421. this._captureAnimationsTime = false;
  96422. this._animationsTime = new BABYLON.PerfCounter();
  96423. // Observers
  96424. this._onBeforeActiveMeshesEvaluationObserver = null;
  96425. this._onAfterActiveMeshesEvaluationObserver = null;
  96426. this._onBeforeRenderTargetsRenderObserver = null;
  96427. this._onAfterRenderTargetsRenderObserver = null;
  96428. this._onAfterRenderObserver = null;
  96429. this._onBeforeDrawPhaseObserver = null;
  96430. this._onAfterDrawPhaseObserver = null;
  96431. this._onBeforeAnimationsObserver = null;
  96432. this._onBeforeParticlesRenderingObserver = null;
  96433. this._onAfterParticlesRenderingObserver = null;
  96434. this._onBeforeSpritesRenderingObserver = null;
  96435. this._onAfterSpritesRenderingObserver = null;
  96436. this._onBeforePhysicsObserver = null;
  96437. this._onAfterPhysicsObserver = null;
  96438. this._onAfterAnimationsObserver = null;
  96439. // Before render
  96440. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  96441. if (_this._captureActiveMeshesEvaluationTime) {
  96442. _this._activeMeshesEvaluationTime.fetchNewFrame();
  96443. }
  96444. if (_this._captureRenderTargetsRenderTime) {
  96445. _this._renderTargetsRenderTime.fetchNewFrame();
  96446. }
  96447. if (_this._captureFrameTime) {
  96448. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  96449. _this._frameTime.beginMonitoring();
  96450. }
  96451. if (_this._captureInterFrameTime) {
  96452. _this._interFrameTime.endMonitoring();
  96453. }
  96454. if (_this._captureParticlesRenderTime) {
  96455. _this._particlesRenderTime.fetchNewFrame();
  96456. }
  96457. if (_this._captureSpritesRenderTime) {
  96458. _this._spritesRenderTime.fetchNewFrame();
  96459. }
  96460. if (_this._captureAnimationsTime) {
  96461. _this._animationsTime.beginMonitoring();
  96462. }
  96463. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  96464. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  96465. });
  96466. // After render
  96467. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  96468. if (_this._captureFrameTime) {
  96469. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  96470. _this._frameTime.endMonitoring();
  96471. }
  96472. if (_this._captureRenderTime) {
  96473. _this._renderTime.endMonitoring(false);
  96474. }
  96475. if (_this._captureInterFrameTime) {
  96476. _this._interFrameTime.beginMonitoring();
  96477. }
  96478. });
  96479. }
  96480. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  96481. // Properties
  96482. /**
  96483. * Gets the perf counter used for active meshes evaluation time
  96484. */
  96485. get: function () {
  96486. return this._activeMeshesEvaluationTime;
  96487. },
  96488. enumerable: true,
  96489. configurable: true
  96490. });
  96491. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  96492. /**
  96493. * Gets the active meshes evaluation time capture status
  96494. */
  96495. get: function () {
  96496. return this._captureActiveMeshesEvaluationTime;
  96497. },
  96498. /**
  96499. * Enable or disable the active meshes evaluation time capture
  96500. */
  96501. set: function (value) {
  96502. var _this = this;
  96503. if (value === this._captureActiveMeshesEvaluationTime) {
  96504. return;
  96505. }
  96506. this._captureActiveMeshesEvaluationTime = value;
  96507. if (value) {
  96508. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  96509. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  96510. _this._activeMeshesEvaluationTime.beginMonitoring();
  96511. });
  96512. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  96513. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  96514. _this._activeMeshesEvaluationTime.endMonitoring();
  96515. });
  96516. }
  96517. else {
  96518. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96519. this._onBeforeActiveMeshesEvaluationObserver = null;
  96520. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96521. this._onAfterActiveMeshesEvaluationObserver = null;
  96522. }
  96523. },
  96524. enumerable: true,
  96525. configurable: true
  96526. });
  96527. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  96528. /**
  96529. * Gets the perf counter used for render targets render time
  96530. */
  96531. get: function () {
  96532. return this._renderTargetsRenderTime;
  96533. },
  96534. enumerable: true,
  96535. configurable: true
  96536. });
  96537. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  96538. /**
  96539. * Gets the render targets render time capture status
  96540. */
  96541. get: function () {
  96542. return this._captureRenderTargetsRenderTime;
  96543. },
  96544. /**
  96545. * Enable or disable the render targets render time capture
  96546. */
  96547. set: function (value) {
  96548. var _this = this;
  96549. if (value === this._captureRenderTargetsRenderTime) {
  96550. return;
  96551. }
  96552. this._captureRenderTargetsRenderTime = value;
  96553. if (value) {
  96554. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  96555. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  96556. _this._renderTargetsRenderTime.beginMonitoring();
  96557. });
  96558. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  96559. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  96560. _this._renderTargetsRenderTime.endMonitoring(false);
  96561. });
  96562. }
  96563. else {
  96564. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96565. this._onBeforeRenderTargetsRenderObserver = null;
  96566. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96567. this._onAfterRenderTargetsRenderObserver = null;
  96568. }
  96569. },
  96570. enumerable: true,
  96571. configurable: true
  96572. });
  96573. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  96574. /**
  96575. * Gets the perf counter used for particles render time
  96576. */
  96577. get: function () {
  96578. return this._particlesRenderTime;
  96579. },
  96580. enumerable: true,
  96581. configurable: true
  96582. });
  96583. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  96584. /**
  96585. * Gets the particles render time capture status
  96586. */
  96587. get: function () {
  96588. return this._captureParticlesRenderTime;
  96589. },
  96590. /**
  96591. * Enable or disable the particles render time capture
  96592. */
  96593. set: function (value) {
  96594. var _this = this;
  96595. if (value === this._captureParticlesRenderTime) {
  96596. return;
  96597. }
  96598. this._captureParticlesRenderTime = value;
  96599. if (value) {
  96600. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  96601. BABYLON.Tools.StartPerformanceCounter("Particles");
  96602. _this._particlesRenderTime.beginMonitoring();
  96603. });
  96604. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  96605. BABYLON.Tools.EndPerformanceCounter("Particles");
  96606. _this._particlesRenderTime.endMonitoring(false);
  96607. });
  96608. }
  96609. else {
  96610. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96611. this._onBeforeParticlesRenderingObserver = null;
  96612. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96613. this._onAfterParticlesRenderingObserver = null;
  96614. }
  96615. },
  96616. enumerable: true,
  96617. configurable: true
  96618. });
  96619. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  96620. /**
  96621. * Gets the perf counter used for sprites render time
  96622. */
  96623. get: function () {
  96624. return this._spritesRenderTime;
  96625. },
  96626. enumerable: true,
  96627. configurable: true
  96628. });
  96629. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  96630. /**
  96631. * Gets the sprites render time capture status
  96632. */
  96633. get: function () {
  96634. return this._captureSpritesRenderTime;
  96635. },
  96636. /**
  96637. * Enable or disable the sprites render time capture
  96638. */
  96639. set: function (value) {
  96640. var _this = this;
  96641. if (value === this._captureSpritesRenderTime) {
  96642. return;
  96643. }
  96644. this._captureSpritesRenderTime = value;
  96645. if (value) {
  96646. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  96647. BABYLON.Tools.StartPerformanceCounter("Sprites");
  96648. _this._spritesRenderTime.beginMonitoring();
  96649. });
  96650. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  96651. BABYLON.Tools.EndPerformanceCounter("Sprites");
  96652. _this._spritesRenderTime.endMonitoring(false);
  96653. });
  96654. }
  96655. else {
  96656. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96657. this._onBeforeSpritesRenderingObserver = null;
  96658. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96659. this._onAfterSpritesRenderingObserver = null;
  96660. }
  96661. },
  96662. enumerable: true,
  96663. configurable: true
  96664. });
  96665. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  96666. /**
  96667. * Gets the perf counter used for physics time
  96668. */
  96669. get: function () {
  96670. return this._physicsTime;
  96671. },
  96672. enumerable: true,
  96673. configurable: true
  96674. });
  96675. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  96676. /**
  96677. * Gets the physics time capture status
  96678. */
  96679. get: function () {
  96680. return this._capturePhysicsTime;
  96681. },
  96682. /**
  96683. * Enable or disable the physics time capture
  96684. */
  96685. set: function (value) {
  96686. var _this = this;
  96687. if (value === this._capturePhysicsTime) {
  96688. return;
  96689. }
  96690. this._capturePhysicsTime = value;
  96691. if (value) {
  96692. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  96693. BABYLON.Tools.StartPerformanceCounter("Physics");
  96694. _this._physicsTime.beginMonitoring();
  96695. });
  96696. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  96697. BABYLON.Tools.EndPerformanceCounter("Physics");
  96698. _this._physicsTime.endMonitoring();
  96699. });
  96700. }
  96701. else {
  96702. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96703. this._onBeforePhysicsObserver = null;
  96704. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96705. this._onAfterPhysicsObserver = null;
  96706. }
  96707. },
  96708. enumerable: true,
  96709. configurable: true
  96710. });
  96711. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  96712. /**
  96713. * Gets the perf counter used for animations time
  96714. */
  96715. get: function () {
  96716. return this._animationsTime;
  96717. },
  96718. enumerable: true,
  96719. configurable: true
  96720. });
  96721. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  96722. /**
  96723. * Gets the animations time capture status
  96724. */
  96725. get: function () {
  96726. return this._captureAnimationsTime;
  96727. },
  96728. /**
  96729. * Enable or disable the animations time capture
  96730. */
  96731. set: function (value) {
  96732. var _this = this;
  96733. if (value === this._captureAnimationsTime) {
  96734. return;
  96735. }
  96736. this._captureAnimationsTime = value;
  96737. if (value) {
  96738. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  96739. _this._animationsTime.endMonitoring();
  96740. });
  96741. }
  96742. else {
  96743. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96744. this._onAfterAnimationsObserver = null;
  96745. }
  96746. },
  96747. enumerable: true,
  96748. configurable: true
  96749. });
  96750. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96751. /**
  96752. * Gets the perf counter used for frame time capture
  96753. */
  96754. get: function () {
  96755. return this._frameTime;
  96756. },
  96757. enumerable: true,
  96758. configurable: true
  96759. });
  96760. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96761. /**
  96762. * Gets the frame time capture status
  96763. */
  96764. get: function () {
  96765. return this._captureFrameTime;
  96766. },
  96767. /**
  96768. * Enable or disable the frame time capture
  96769. */
  96770. set: function (value) {
  96771. this._captureFrameTime = value;
  96772. },
  96773. enumerable: true,
  96774. configurable: true
  96775. });
  96776. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96777. /**
  96778. * Gets the perf counter used for inter-frames time capture
  96779. */
  96780. get: function () {
  96781. return this._interFrameTime;
  96782. },
  96783. enumerable: true,
  96784. configurable: true
  96785. });
  96786. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96787. /**
  96788. * Gets the inter-frames time capture status
  96789. */
  96790. get: function () {
  96791. return this._captureInterFrameTime;
  96792. },
  96793. /**
  96794. * Enable or disable the inter-frames time capture
  96795. */
  96796. set: function (value) {
  96797. this._captureInterFrameTime = value;
  96798. },
  96799. enumerable: true,
  96800. configurable: true
  96801. });
  96802. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96803. /**
  96804. * Gets the perf counter used for render time capture
  96805. */
  96806. get: function () {
  96807. return this._renderTime;
  96808. },
  96809. enumerable: true,
  96810. configurable: true
  96811. });
  96812. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96813. /**
  96814. * Gets the render time capture status
  96815. */
  96816. get: function () {
  96817. return this._captureRenderTime;
  96818. },
  96819. /**
  96820. * Enable or disable the render time capture
  96821. */
  96822. set: function (value) {
  96823. var _this = this;
  96824. if (value === this._captureRenderTime) {
  96825. return;
  96826. }
  96827. this._captureRenderTime = value;
  96828. if (value) {
  96829. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96830. _this._renderTime.beginMonitoring();
  96831. BABYLON.Tools.StartPerformanceCounter("Main render");
  96832. });
  96833. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96834. _this._renderTime.endMonitoring(false);
  96835. BABYLON.Tools.EndPerformanceCounter("Main render");
  96836. });
  96837. }
  96838. else {
  96839. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96840. this._onBeforeDrawPhaseObserver = null;
  96841. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96842. this._onAfterDrawPhaseObserver = null;
  96843. }
  96844. },
  96845. enumerable: true,
  96846. configurable: true
  96847. });
  96848. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96849. /**
  96850. * Gets the perf counter used for draw calls
  96851. */
  96852. get: function () {
  96853. return this.scene.getEngine()._drawCalls;
  96854. },
  96855. enumerable: true,
  96856. configurable: true
  96857. });
  96858. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96859. /**
  96860. * Gets the perf counter used for texture collisions
  96861. */
  96862. get: function () {
  96863. return this.scene.getEngine()._textureCollisions;
  96864. },
  96865. enumerable: true,
  96866. configurable: true
  96867. });
  96868. SceneInstrumentation.prototype.dispose = function () {
  96869. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96870. this._onAfterRenderObserver = null;
  96871. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96872. this._onBeforeActiveMeshesEvaluationObserver = null;
  96873. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96874. this._onAfterActiveMeshesEvaluationObserver = null;
  96875. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96876. this._onBeforeRenderTargetsRenderObserver = null;
  96877. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96878. this._onAfterRenderTargetsRenderObserver = null;
  96879. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96880. this._onBeforeAnimationsObserver = null;
  96881. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96882. this._onBeforeParticlesRenderingObserver = null;
  96883. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96884. this._onAfterParticlesRenderingObserver = null;
  96885. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96886. this._onBeforeSpritesRenderingObserver = null;
  96887. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96888. this._onAfterSpritesRenderingObserver = null;
  96889. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96890. this._onBeforeDrawPhaseObserver = null;
  96891. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96892. this._onAfterDrawPhaseObserver = null;
  96893. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96894. this._onBeforePhysicsObserver = null;
  96895. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96896. this._onAfterPhysicsObserver = null;
  96897. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96898. this._onAfterAnimationsObserver = null;
  96899. this.scene = null;
  96900. };
  96901. return SceneInstrumentation;
  96902. }());
  96903. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96904. })(BABYLON || (BABYLON = {}));
  96905. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96906. var BABYLON;
  96907. (function (BABYLON) {
  96908. /**
  96909. * @hidden
  96910. **/
  96911. var _TimeToken = /** @class */ (function () {
  96912. function _TimeToken() {
  96913. this._timeElapsedQueryEnded = false;
  96914. }
  96915. return _TimeToken;
  96916. }());
  96917. BABYLON._TimeToken = _TimeToken;
  96918. })(BABYLON || (BABYLON = {}));
  96919. //# sourceMappingURL=babylon.timeToken.js.map
  96920. var BABYLON;
  96921. (function (BABYLON) {
  96922. /**
  96923. * Background material defines definition.
  96924. * @hidden Mainly internal Use
  96925. */
  96926. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96927. __extends(BackgroundMaterialDefines, _super);
  96928. /**
  96929. * Constructor of the defines.
  96930. */
  96931. function BackgroundMaterialDefines() {
  96932. var _this = _super.call(this) || this;
  96933. /**
  96934. * True if the diffuse texture is in use.
  96935. */
  96936. _this.DIFFUSE = false;
  96937. /**
  96938. * The direct UV channel to use.
  96939. */
  96940. _this.DIFFUSEDIRECTUV = 0;
  96941. /**
  96942. * True if the diffuse texture is in gamma space.
  96943. */
  96944. _this.GAMMADIFFUSE = false;
  96945. /**
  96946. * True if the diffuse texture has opacity in the alpha channel.
  96947. */
  96948. _this.DIFFUSEHASALPHA = false;
  96949. /**
  96950. * True if you want the material to fade to transparent at grazing angle.
  96951. */
  96952. _this.OPACITYFRESNEL = false;
  96953. /**
  96954. * True if an extra blur needs to be added in the reflection.
  96955. */
  96956. _this.REFLECTIONBLUR = false;
  96957. /**
  96958. * True if you want the material to fade to reflection at grazing angle.
  96959. */
  96960. _this.REFLECTIONFRESNEL = false;
  96961. /**
  96962. * True if you want the material to falloff as far as you move away from the scene center.
  96963. */
  96964. _this.REFLECTIONFALLOFF = false;
  96965. /**
  96966. * False if the current Webgl implementation does not support the texture lod extension.
  96967. */
  96968. _this.TEXTURELODSUPPORT = false;
  96969. /**
  96970. * True to ensure the data are premultiplied.
  96971. */
  96972. _this.PREMULTIPLYALPHA = false;
  96973. /**
  96974. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96975. */
  96976. _this.USERGBCOLOR = false;
  96977. /**
  96978. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96979. * stays aligned with the desired configuration.
  96980. */
  96981. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96982. /**
  96983. * True to add noise in order to reduce the banding effect.
  96984. */
  96985. _this.NOISE = false;
  96986. /**
  96987. * is the reflection texture in BGR color scheme?
  96988. * Mainly used to solve a bug in ios10 video tag
  96989. */
  96990. _this.REFLECTIONBGR = false;
  96991. _this.IMAGEPROCESSING = false;
  96992. _this.VIGNETTE = false;
  96993. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96994. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96995. _this.TONEMAPPING = false;
  96996. _this.CONTRAST = false;
  96997. _this.COLORCURVES = false;
  96998. _this.COLORGRADING = false;
  96999. _this.COLORGRADING3D = false;
  97000. _this.SAMPLER3DGREENDEPTH = false;
  97001. _this.SAMPLER3DBGRMAP = false;
  97002. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  97003. _this.EXPOSURE = false;
  97004. // Reflection.
  97005. _this.REFLECTION = false;
  97006. _this.REFLECTIONMAP_3D = false;
  97007. _this.REFLECTIONMAP_SPHERICAL = false;
  97008. _this.REFLECTIONMAP_PLANAR = false;
  97009. _this.REFLECTIONMAP_CUBIC = false;
  97010. _this.REFLECTIONMAP_PROJECTION = false;
  97011. _this.REFLECTIONMAP_SKYBOX = false;
  97012. _this.REFLECTIONMAP_EXPLICIT = false;
  97013. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97014. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97015. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97016. _this.INVERTCUBICMAP = false;
  97017. _this.REFLECTIONMAP_OPPOSITEZ = false;
  97018. _this.LODINREFLECTIONALPHA = false;
  97019. _this.GAMMAREFLECTION = false;
  97020. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  97021. // Default BJS.
  97022. _this.MAINUV1 = false;
  97023. _this.MAINUV2 = false;
  97024. _this.UV1 = false;
  97025. _this.UV2 = false;
  97026. _this.CLIPPLANE = false;
  97027. _this.POINTSIZE = false;
  97028. _this.FOG = false;
  97029. _this.NORMAL = false;
  97030. _this.NUM_BONE_INFLUENCERS = 0;
  97031. _this.BonesPerMesh = 0;
  97032. _this.INSTANCES = false;
  97033. _this.SHADOWFLOAT = false;
  97034. _this.rebuild();
  97035. return _this;
  97036. }
  97037. return BackgroundMaterialDefines;
  97038. }(BABYLON.MaterialDefines));
  97039. /**
  97040. * Background material used to create an efficient environement around your scene.
  97041. */
  97042. var BackgroundMaterial = /** @class */ (function (_super) {
  97043. __extends(BackgroundMaterial, _super);
  97044. /**
  97045. * Instantiates a Background Material in the given scene
  97046. * @param name The friendly name of the material
  97047. * @param scene The scene to add the material to
  97048. */
  97049. function BackgroundMaterial(name, scene) {
  97050. var _this = _super.call(this, name, scene) || this;
  97051. /**
  97052. * Key light Color (multiply against the environement texture)
  97053. */
  97054. _this.primaryColor = BABYLON.Color3.White();
  97055. _this._primaryColorShadowLevel = 0;
  97056. _this._primaryColorHighlightLevel = 0;
  97057. /**
  97058. * Reflection Texture used in the material.
  97059. * Should be author in a specific way for the best result (refer to the documentation).
  97060. */
  97061. _this.reflectionTexture = null;
  97062. /**
  97063. * Reflection Texture level of blur.
  97064. *
  97065. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  97066. * texture twice.
  97067. */
  97068. _this.reflectionBlur = 0;
  97069. /**
  97070. * Diffuse Texture used in the material.
  97071. * Should be author in a specific way for the best result (refer to the documentation).
  97072. */
  97073. _this.diffuseTexture = null;
  97074. _this._shadowLights = null;
  97075. /**
  97076. * Specify the list of lights casting shadow on the material.
  97077. * All scene shadow lights will be included if null.
  97078. */
  97079. _this.shadowLights = null;
  97080. /**
  97081. * Helps adjusting the shadow to a softer level if required.
  97082. * 0 means black shadows and 1 means no shadows.
  97083. */
  97084. _this.shadowLevel = 0;
  97085. /**
  97086. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  97087. * It is usually zero but might be interesting to modify according to your setup.
  97088. */
  97089. _this.sceneCenter = BABYLON.Vector3.Zero();
  97090. /**
  97091. * This helps specifying that the material is falling off to the sky box at grazing angle.
  97092. * This helps ensuring a nice transition when the camera goes under the ground.
  97093. */
  97094. _this.opacityFresnel = true;
  97095. /**
  97096. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  97097. * This helps adding a mirror texture on the ground.
  97098. */
  97099. _this.reflectionFresnel = false;
  97100. /**
  97101. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  97102. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  97103. */
  97104. _this.reflectionFalloffDistance = 0.0;
  97105. /**
  97106. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  97107. */
  97108. _this.reflectionAmount = 1.0;
  97109. /**
  97110. * This specifies the weight of the reflection at grazing angle.
  97111. */
  97112. _this.reflectionReflectance0 = 0.05;
  97113. /**
  97114. * This specifies the weight of the reflection at a perpendicular point of view.
  97115. */
  97116. _this.reflectionReflectance90 = 0.5;
  97117. /**
  97118. * Helps to directly use the maps channels instead of their level.
  97119. */
  97120. _this.useRGBColor = true;
  97121. /**
  97122. * This helps reducing the banding effect that could occur on the background.
  97123. */
  97124. _this.enableNoise = false;
  97125. _this._fovMultiplier = 1.0;
  97126. /**
  97127. * Enable the FOV adjustment feature controlled by fovMultiplier.
  97128. */
  97129. _this.useEquirectangularFOV = false;
  97130. _this._maxSimultaneousLights = 4;
  97131. /**
  97132. * Number of Simultaneous lights allowed on the material.
  97133. */
  97134. _this.maxSimultaneousLights = 4;
  97135. /**
  97136. * Keep track of the image processing observer to allow dispose and replace.
  97137. */
  97138. _this._imageProcessingObserver = null;
  97139. /**
  97140. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  97141. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  97142. */
  97143. _this.switchToBGR = false;
  97144. // Temp values kept as cache in the material.
  97145. _this._renderTargets = new BABYLON.SmartArray(16);
  97146. _this._reflectionControls = BABYLON.Vector4.Zero();
  97147. _this._white = BABYLON.Color3.White();
  97148. _this._primaryShadowColor = BABYLON.Color3.Black();
  97149. _this._primaryHighlightColor = BABYLON.Color3.Black();
  97150. // Setup the default processing configuration to the scene.
  97151. _this._attachImageProcessingConfiguration(null);
  97152. _this.getRenderTargetTextures = function () {
  97153. _this._renderTargets.reset();
  97154. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  97155. _this._renderTargets.push(_this._diffuseTexture);
  97156. }
  97157. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  97158. _this._renderTargets.push(_this._reflectionTexture);
  97159. }
  97160. return _this._renderTargets;
  97161. };
  97162. return _this;
  97163. }
  97164. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  97165. /**
  97166. * Experimental Internal Use Only.
  97167. *
  97168. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  97169. * This acts as a helper to set the primary color to a more "human friendly" value.
  97170. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  97171. * output color as close as possible from the chosen value.
  97172. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  97173. * part of lighting setup.)
  97174. */
  97175. get: function () {
  97176. return this.__perceptualColor;
  97177. },
  97178. set: function (value) {
  97179. this.__perceptualColor = value;
  97180. this._computePrimaryColorFromPerceptualColor();
  97181. this._markAllSubMeshesAsLightsDirty();
  97182. },
  97183. enumerable: true,
  97184. configurable: true
  97185. });
  97186. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  97187. /**
  97188. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  97189. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  97190. */
  97191. get: function () {
  97192. return this._primaryColorShadowLevel;
  97193. },
  97194. set: function (value) {
  97195. this._primaryColorShadowLevel = value;
  97196. this._computePrimaryColors();
  97197. this._markAllSubMeshesAsLightsDirty();
  97198. },
  97199. enumerable: true,
  97200. configurable: true
  97201. });
  97202. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  97203. /**
  97204. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  97205. * The primary color is used at the level chosen to define what the white area would look.
  97206. */
  97207. get: function () {
  97208. return this._primaryColorHighlightLevel;
  97209. },
  97210. set: function (value) {
  97211. this._primaryColorHighlightLevel = value;
  97212. this._computePrimaryColors();
  97213. this._markAllSubMeshesAsLightsDirty();
  97214. },
  97215. enumerable: true,
  97216. configurable: true
  97217. });
  97218. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  97219. /**
  97220. * Sets the reflection reflectance fresnel values according to the default standard
  97221. * empirically know to work well :-)
  97222. */
  97223. set: function (value) {
  97224. var reflectionWeight = value;
  97225. if (reflectionWeight < 0.5) {
  97226. reflectionWeight = reflectionWeight * 2.0;
  97227. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  97228. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  97229. }
  97230. else {
  97231. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  97232. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  97233. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  97234. }
  97235. },
  97236. enumerable: true,
  97237. configurable: true
  97238. });
  97239. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  97240. /**
  97241. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97242. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  97243. * Recommended to be keep at 1.0 except for special cases.
  97244. */
  97245. get: function () {
  97246. return this._fovMultiplier;
  97247. },
  97248. set: function (value) {
  97249. if (isNaN(value)) {
  97250. value = 1.0;
  97251. }
  97252. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  97253. },
  97254. enumerable: true,
  97255. configurable: true
  97256. });
  97257. /**
  97258. * Attaches a new image processing configuration to the PBR Material.
  97259. * @param configuration (if null the scene configuration will be use)
  97260. */
  97261. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  97262. var _this = this;
  97263. if (configuration === this._imageProcessingConfiguration) {
  97264. return;
  97265. }
  97266. // Detaches observer.
  97267. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97268. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97269. }
  97270. // Pick the scene configuration if needed.
  97271. if (!configuration) {
  97272. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  97273. }
  97274. else {
  97275. this._imageProcessingConfiguration = configuration;
  97276. }
  97277. // Attaches observer.
  97278. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  97279. _this._computePrimaryColorFromPerceptualColor();
  97280. _this._markAllSubMeshesAsImageProcessingDirty();
  97281. });
  97282. };
  97283. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  97284. /**
  97285. * Gets the image processing configuration used either in this material.
  97286. */
  97287. get: function () {
  97288. return this._imageProcessingConfiguration;
  97289. },
  97290. /**
  97291. * Sets the Default image processing configuration used either in the this material.
  97292. *
  97293. * If sets to null, the scene one is in use.
  97294. */
  97295. set: function (value) {
  97296. this._attachImageProcessingConfiguration(value);
  97297. // Ensure the effect will be rebuilt.
  97298. this._markAllSubMeshesAsTexturesDirty();
  97299. },
  97300. enumerable: true,
  97301. configurable: true
  97302. });
  97303. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  97304. /**
  97305. * Gets wether the color curves effect is enabled.
  97306. */
  97307. get: function () {
  97308. return this.imageProcessingConfiguration.colorCurvesEnabled;
  97309. },
  97310. /**
  97311. * Sets wether the color curves effect is enabled.
  97312. */
  97313. set: function (value) {
  97314. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  97315. },
  97316. enumerable: true,
  97317. configurable: true
  97318. });
  97319. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  97320. /**
  97321. * Gets wether the color grading effect is enabled.
  97322. */
  97323. get: function () {
  97324. return this.imageProcessingConfiguration.colorGradingEnabled;
  97325. },
  97326. /**
  97327. * Gets wether the color grading effect is enabled.
  97328. */
  97329. set: function (value) {
  97330. this.imageProcessingConfiguration.colorGradingEnabled = value;
  97331. },
  97332. enumerable: true,
  97333. configurable: true
  97334. });
  97335. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  97336. /**
  97337. * Gets wether tonemapping is enabled or not.
  97338. */
  97339. get: function () {
  97340. return this._imageProcessingConfiguration.toneMappingEnabled;
  97341. },
  97342. /**
  97343. * Sets wether tonemapping is enabled or not
  97344. */
  97345. set: function (value) {
  97346. this._imageProcessingConfiguration.toneMappingEnabled = value;
  97347. },
  97348. enumerable: true,
  97349. configurable: true
  97350. });
  97351. ;
  97352. ;
  97353. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  97354. /**
  97355. * The camera exposure used on this material.
  97356. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97357. * This corresponds to a photographic exposure.
  97358. */
  97359. get: function () {
  97360. return this._imageProcessingConfiguration.exposure;
  97361. },
  97362. /**
  97363. * The camera exposure used on this material.
  97364. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97365. * This corresponds to a photographic exposure.
  97366. */
  97367. set: function (value) {
  97368. this._imageProcessingConfiguration.exposure = value;
  97369. },
  97370. enumerable: true,
  97371. configurable: true
  97372. });
  97373. ;
  97374. ;
  97375. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  97376. /**
  97377. * Gets The camera contrast used on this material.
  97378. */
  97379. get: function () {
  97380. return this._imageProcessingConfiguration.contrast;
  97381. },
  97382. /**
  97383. * Sets The camera contrast used on this material.
  97384. */
  97385. set: function (value) {
  97386. this._imageProcessingConfiguration.contrast = value;
  97387. },
  97388. enumerable: true,
  97389. configurable: true
  97390. });
  97391. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  97392. /**
  97393. * Gets the Color Grading 2D Lookup Texture.
  97394. */
  97395. get: function () {
  97396. return this._imageProcessingConfiguration.colorGradingTexture;
  97397. },
  97398. /**
  97399. * Sets the Color Grading 2D Lookup Texture.
  97400. */
  97401. set: function (value) {
  97402. this.imageProcessingConfiguration.colorGradingTexture = value;
  97403. },
  97404. enumerable: true,
  97405. configurable: true
  97406. });
  97407. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  97408. /**
  97409. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97410. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97411. * 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;
  97412. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97413. */
  97414. get: function () {
  97415. return this.imageProcessingConfiguration.colorCurves;
  97416. },
  97417. /**
  97418. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  97419. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  97420. * 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;
  97421. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  97422. */
  97423. set: function (value) {
  97424. this.imageProcessingConfiguration.colorCurves = value;
  97425. },
  97426. enumerable: true,
  97427. configurable: true
  97428. });
  97429. /**
  97430. * The entire material has been created in order to prevent overdraw.
  97431. * @returns false
  97432. */
  97433. BackgroundMaterial.prototype.needAlphaTesting = function () {
  97434. return true;
  97435. };
  97436. /**
  97437. * The entire material has been created in order to prevent overdraw.
  97438. * @returns true if blending is enable
  97439. */
  97440. BackgroundMaterial.prototype.needAlphaBlending = function () {
  97441. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  97442. };
  97443. /**
  97444. * Checks wether the material is ready to be rendered for a given mesh.
  97445. * @param mesh The mesh to render
  97446. * @param subMesh The submesh to check against
  97447. * @param useInstances Specify wether or not the material is used with instances
  97448. * @returns true if all the dependencies are ready (Textures, Effects...)
  97449. */
  97450. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  97451. var _this = this;
  97452. if (useInstances === void 0) { useInstances = false; }
  97453. if (subMesh.effect && this.isFrozen) {
  97454. if (this._wasPreviouslyReady) {
  97455. return true;
  97456. }
  97457. }
  97458. if (!subMesh._materialDefines) {
  97459. subMesh._materialDefines = new BackgroundMaterialDefines();
  97460. }
  97461. var scene = this.getScene();
  97462. var defines = subMesh._materialDefines;
  97463. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  97464. if (defines._renderId === scene.getRenderId()) {
  97465. return true;
  97466. }
  97467. }
  97468. var engine = scene.getEngine();
  97469. // Lights
  97470. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  97471. defines._needNormals = true;
  97472. // Textures
  97473. if (defines._areTexturesDirty) {
  97474. defines._needUVs = false;
  97475. if (scene.texturesEnabled) {
  97476. if (scene.getEngine().getCaps().textureLOD) {
  97477. defines.TEXTURELODSUPPORT = true;
  97478. }
  97479. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97480. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  97481. return false;
  97482. }
  97483. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  97484. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  97485. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  97486. defines.OPACITYFRESNEL = this._opacityFresnel;
  97487. }
  97488. else {
  97489. defines.DIFFUSE = false;
  97490. defines.DIFFUSEHASALPHA = false;
  97491. defines.GAMMADIFFUSE = false;
  97492. defines.OPACITYFRESNEL = false;
  97493. }
  97494. var reflectionTexture = this._reflectionTexture;
  97495. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97496. if (!reflectionTexture.isReadyOrNotBlocking()) {
  97497. return false;
  97498. }
  97499. defines.REFLECTION = true;
  97500. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  97501. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  97502. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  97503. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  97504. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  97505. defines.REFLECTIONBGR = this.switchToBGR;
  97506. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  97507. defines.INVERTCUBICMAP = true;
  97508. }
  97509. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  97510. switch (reflectionTexture.coordinatesMode) {
  97511. case BABYLON.Texture.EXPLICIT_MODE:
  97512. defines.REFLECTIONMAP_EXPLICIT = true;
  97513. break;
  97514. case BABYLON.Texture.PLANAR_MODE:
  97515. defines.REFLECTIONMAP_PLANAR = true;
  97516. break;
  97517. case BABYLON.Texture.PROJECTION_MODE:
  97518. defines.REFLECTIONMAP_PROJECTION = true;
  97519. break;
  97520. case BABYLON.Texture.SKYBOX_MODE:
  97521. defines.REFLECTIONMAP_SKYBOX = true;
  97522. break;
  97523. case BABYLON.Texture.SPHERICAL_MODE:
  97524. defines.REFLECTIONMAP_SPHERICAL = true;
  97525. break;
  97526. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  97527. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  97528. break;
  97529. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  97530. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  97531. break;
  97532. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  97533. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  97534. break;
  97535. case BABYLON.Texture.CUBIC_MODE:
  97536. case BABYLON.Texture.INVCUBIC_MODE:
  97537. default:
  97538. defines.REFLECTIONMAP_CUBIC = true;
  97539. break;
  97540. }
  97541. if (this.reflectionFresnel) {
  97542. defines.REFLECTIONFRESNEL = true;
  97543. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  97544. this._reflectionControls.x = this.reflectionAmount;
  97545. this._reflectionControls.y = this.reflectionReflectance0;
  97546. this._reflectionControls.z = this.reflectionReflectance90;
  97547. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  97548. }
  97549. else {
  97550. defines.REFLECTIONFRESNEL = false;
  97551. defines.REFLECTIONFALLOFF = false;
  97552. }
  97553. }
  97554. else {
  97555. defines.REFLECTION = false;
  97556. defines.REFLECTIONFRESNEL = false;
  97557. defines.REFLECTIONFALLOFF = false;
  97558. defines.REFLECTIONBLUR = false;
  97559. defines.REFLECTIONMAP_3D = false;
  97560. defines.REFLECTIONMAP_SPHERICAL = false;
  97561. defines.REFLECTIONMAP_PLANAR = false;
  97562. defines.REFLECTIONMAP_CUBIC = false;
  97563. defines.REFLECTIONMAP_PROJECTION = false;
  97564. defines.REFLECTIONMAP_SKYBOX = false;
  97565. defines.REFLECTIONMAP_EXPLICIT = false;
  97566. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97567. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97568. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97569. defines.INVERTCUBICMAP = false;
  97570. defines.REFLECTIONMAP_OPPOSITEZ = false;
  97571. defines.LODINREFLECTIONALPHA = false;
  97572. defines.GAMMAREFLECTION = false;
  97573. }
  97574. }
  97575. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  97576. defines.USERGBCOLOR = this._useRGBColor;
  97577. defines.NOISE = this._enableNoise;
  97578. }
  97579. if (defines._areLightsDirty) {
  97580. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  97581. }
  97582. if (defines._areImageProcessingDirty) {
  97583. if (!this._imageProcessingConfiguration.isReady()) {
  97584. return false;
  97585. }
  97586. this._imageProcessingConfiguration.prepareDefines(defines);
  97587. }
  97588. // Misc.
  97589. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  97590. // Values that need to be evaluated on every frame
  97591. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  97592. // Attribs
  97593. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  97594. if (mesh) {
  97595. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97596. mesh.createNormals(true);
  97597. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  97598. }
  97599. }
  97600. }
  97601. // Get correct effect
  97602. if (defines.isDirty) {
  97603. defines.markAsProcessed();
  97604. scene.resetCachedMaterial();
  97605. // Fallbacks
  97606. var fallbacks = new BABYLON.EffectFallbacks();
  97607. if (defines.FOG) {
  97608. fallbacks.addFallback(0, "FOG");
  97609. }
  97610. if (defines.POINTSIZE) {
  97611. fallbacks.addFallback(1, "POINTSIZE");
  97612. }
  97613. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  97614. if (defines.NUM_BONE_INFLUENCERS > 0) {
  97615. fallbacks.addCPUSkinningFallback(0, mesh);
  97616. }
  97617. //Attributes
  97618. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97619. if (defines.NORMAL) {
  97620. attribs.push(BABYLON.VertexBuffer.NormalKind);
  97621. }
  97622. if (defines.UV1) {
  97623. attribs.push(BABYLON.VertexBuffer.UVKind);
  97624. }
  97625. if (defines.UV2) {
  97626. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97627. }
  97628. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  97629. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  97630. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  97631. "vFogInfos", "vFogColor", "pointSize",
  97632. "vClipPlane", "mBones",
  97633. "vPrimaryColor", "vPrimaryColorShadow",
  97634. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  97635. "shadowLevel", "alpha",
  97636. "vBackgroundCenter", "vReflectionControl",
  97637. "vDiffuseInfos", "diffuseMatrix",
  97638. ];
  97639. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  97640. var uniformBuffers = ["Material", "Scene"];
  97641. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  97642. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  97643. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  97644. uniformsNames: uniforms,
  97645. uniformBuffersNames: uniformBuffers,
  97646. samplers: samplers,
  97647. defines: defines,
  97648. maxSimultaneousLights: this._maxSimultaneousLights
  97649. });
  97650. var onCompiled = function (effect) {
  97651. if (_this.onCompiled) {
  97652. _this.onCompiled(effect);
  97653. }
  97654. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  97655. };
  97656. var join = defines.toString();
  97657. subMesh.setEffect(scene.getEngine().createEffect("background", {
  97658. attributes: attribs,
  97659. uniformsNames: uniforms,
  97660. uniformBuffersNames: uniformBuffers,
  97661. samplers: samplers,
  97662. defines: join,
  97663. fallbacks: fallbacks,
  97664. onCompiled: onCompiled,
  97665. onError: this.onError,
  97666. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  97667. }, engine), defines);
  97668. this.buildUniformLayout();
  97669. }
  97670. if (!subMesh.effect || !subMesh.effect.isReady()) {
  97671. return false;
  97672. }
  97673. defines._renderId = scene.getRenderId();
  97674. this._wasPreviouslyReady = true;
  97675. return true;
  97676. };
  97677. /**
  97678. * Compute the primary color according to the chosen perceptual color.
  97679. */
  97680. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  97681. if (!this.__perceptualColor) {
  97682. return;
  97683. }
  97684. this._primaryColor.copyFrom(this.__perceptualColor);
  97685. // Revert gamma space.
  97686. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  97687. // Revert image processing configuration.
  97688. if (this._imageProcessingConfiguration) {
  97689. // Revert Exposure.
  97690. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  97691. }
  97692. this._computePrimaryColors();
  97693. };
  97694. /**
  97695. * Compute the highlights and shadow colors according to their chosen levels.
  97696. */
  97697. BackgroundMaterial.prototype._computePrimaryColors = function () {
  97698. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  97699. return;
  97700. }
  97701. // Find the highlight color based on the configuration.
  97702. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  97703. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  97704. // Find the shadow color based on the configuration.
  97705. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  97706. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  97707. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  97708. };
  97709. /**
  97710. * Build the uniform buffer used in the material.
  97711. */
  97712. BackgroundMaterial.prototype.buildUniformLayout = function () {
  97713. // Order is important !
  97714. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  97715. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  97716. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  97717. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  97718. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  97719. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  97720. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  97721. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  97722. this._uniformBuffer.addUniform("pointSize", 1);
  97723. this._uniformBuffer.addUniform("shadowLevel", 1);
  97724. this._uniformBuffer.addUniform("alpha", 1);
  97725. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  97726. this._uniformBuffer.addUniform("vReflectionControl", 4);
  97727. this._uniformBuffer.create();
  97728. };
  97729. /**
  97730. * Unbind the material.
  97731. */
  97732. BackgroundMaterial.prototype.unbind = function () {
  97733. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  97734. this._uniformBuffer.setTexture("diffuseSampler", null);
  97735. }
  97736. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  97737. this._uniformBuffer.setTexture("reflectionSampler", null);
  97738. }
  97739. _super.prototype.unbind.call(this);
  97740. };
  97741. /**
  97742. * Bind only the world matrix to the material.
  97743. * @param world The world matrix to bind.
  97744. */
  97745. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  97746. this._activeEffect.setMatrix("world", world);
  97747. };
  97748. /**
  97749. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97750. * @param world The world matrix to bind.
  97751. * @param subMesh The submesh to bind for.
  97752. */
  97753. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97754. var scene = this.getScene();
  97755. var defines = subMesh._materialDefines;
  97756. if (!defines) {
  97757. return;
  97758. }
  97759. var effect = subMesh.effect;
  97760. if (!effect) {
  97761. return;
  97762. }
  97763. this._activeEffect = effect;
  97764. // Matrices
  97765. this.bindOnlyWorldMatrix(world);
  97766. // Bones
  97767. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97768. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97769. if (mustRebind) {
  97770. this._uniformBuffer.bindToEffect(effect, "Material");
  97771. this.bindViewProjection(effect);
  97772. var reflectionTexture = this._reflectionTexture;
  97773. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97774. // Texture uniforms
  97775. if (scene.texturesEnabled) {
  97776. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97777. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97778. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97779. }
  97780. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97781. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97782. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97783. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97784. }
  97785. }
  97786. if (this.shadowLevel > 0) {
  97787. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97788. }
  97789. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97790. // Point size
  97791. if (this.pointsCloud) {
  97792. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97793. }
  97794. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97795. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97796. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97797. }
  97798. else {
  97799. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97800. }
  97801. }
  97802. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97803. // Textures
  97804. if (scene.texturesEnabled) {
  97805. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97806. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97807. }
  97808. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97809. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97810. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97811. }
  97812. else if (!defines.REFLECTIONBLUR) {
  97813. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97814. }
  97815. else {
  97816. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97817. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97818. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97819. }
  97820. if (defines.REFLECTIONFRESNEL) {
  97821. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97822. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97823. }
  97824. }
  97825. }
  97826. // Clip plane
  97827. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97828. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97829. }
  97830. if (mustRebind || !this.isFrozen) {
  97831. if (scene.lightsEnabled) {
  97832. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97833. }
  97834. // View
  97835. this.bindView(effect);
  97836. // Fog
  97837. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97838. // image processing
  97839. this._imageProcessingConfiguration.bind(this._activeEffect);
  97840. }
  97841. this._uniformBuffer.update();
  97842. this._afterBind(mesh);
  97843. };
  97844. /**
  97845. * Dispose the material.
  97846. * @param forceDisposeEffect Force disposal of the associated effect.
  97847. * @param forceDisposeTextures Force disposal of the associated textures.
  97848. */
  97849. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97850. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97851. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97852. if (forceDisposeTextures) {
  97853. if (this.diffuseTexture) {
  97854. this.diffuseTexture.dispose();
  97855. }
  97856. if (this.reflectionTexture) {
  97857. this.reflectionTexture.dispose();
  97858. }
  97859. }
  97860. this._renderTargets.dispose();
  97861. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97862. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97863. }
  97864. _super.prototype.dispose.call(this, forceDisposeEffect);
  97865. };
  97866. /**
  97867. * Clones the material.
  97868. * @param name The cloned name.
  97869. * @returns The cloned material.
  97870. */
  97871. BackgroundMaterial.prototype.clone = function (name) {
  97872. var _this = this;
  97873. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97874. };
  97875. /**
  97876. * Serializes the current material to its JSON representation.
  97877. * @returns The JSON representation.
  97878. */
  97879. BackgroundMaterial.prototype.serialize = function () {
  97880. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97881. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97882. return serializationObject;
  97883. };
  97884. /**
  97885. * Gets the class name of the material
  97886. * @returns "BackgroundMaterial"
  97887. */
  97888. BackgroundMaterial.prototype.getClassName = function () {
  97889. return "BackgroundMaterial";
  97890. };
  97891. /**
  97892. * Parse a JSON input to create back a background material.
  97893. * @param source The JSON data to parse
  97894. * @param scene The scene to create the parsed material in
  97895. * @param rootUrl The root url of the assets the material depends upon
  97896. * @returns the instantiated BackgroundMaterial.
  97897. */
  97898. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97899. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97900. };
  97901. /**
  97902. * Standard reflectance value at parallel view angle.
  97903. */
  97904. BackgroundMaterial.StandardReflectance0 = 0.05;
  97905. /**
  97906. * Standard reflectance value at grazing angle.
  97907. */
  97908. BackgroundMaterial.StandardReflectance90 = 0.5;
  97909. __decorate([
  97910. BABYLON.serializeAsColor3()
  97911. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97912. __decorate([
  97913. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97914. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97915. __decorate([
  97916. BABYLON.serializeAsColor3()
  97917. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97918. __decorate([
  97919. BABYLON.serialize()
  97920. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97921. __decorate([
  97922. BABYLON.serialize()
  97923. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97924. __decorate([
  97925. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97926. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97927. __decorate([
  97928. BABYLON.serializeAsTexture()
  97929. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97930. __decorate([
  97931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97932. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97933. __decorate([
  97934. BABYLON.serialize()
  97935. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97936. __decorate([
  97937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97938. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97939. __decorate([
  97940. BABYLON.serializeAsTexture()
  97941. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97942. __decorate([
  97943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97944. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97945. __decorate([
  97946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97947. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97948. __decorate([
  97949. BABYLON.serialize()
  97950. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97951. __decorate([
  97952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97953. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97954. __decorate([
  97955. BABYLON.serializeAsVector3()
  97956. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97957. __decorate([
  97958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97959. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97960. __decorate([
  97961. BABYLON.serialize()
  97962. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97963. __decorate([
  97964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97965. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97966. __decorate([
  97967. BABYLON.serialize()
  97968. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97969. __decorate([
  97970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97971. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97972. __decorate([
  97973. BABYLON.serialize()
  97974. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97975. __decorate([
  97976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97977. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97978. __decorate([
  97979. BABYLON.serialize()
  97980. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97981. __decorate([
  97982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97983. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97984. __decorate([
  97985. BABYLON.serialize()
  97986. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97987. __decorate([
  97988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97989. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97990. __decorate([
  97991. BABYLON.serialize()
  97992. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97993. __decorate([
  97994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97995. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97996. __decorate([
  97997. BABYLON.serialize()
  97998. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97999. __decorate([
  98000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98001. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  98002. __decorate([
  98003. BABYLON.serialize()
  98004. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  98005. __decorate([
  98006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98007. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  98008. __decorate([
  98009. BABYLON.serialize()
  98010. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  98011. __decorate([
  98012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98013. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  98014. __decorate([
  98015. BABYLON.serializeAsImageProcessingConfiguration()
  98016. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  98017. return BackgroundMaterial;
  98018. }(BABYLON.PushMaterial));
  98019. BABYLON.BackgroundMaterial = BackgroundMaterial;
  98020. })(BABYLON || (BABYLON = {}));
  98021. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  98022. var __assign = (this && this.__assign) || Object.assign || function(t) {
  98023. for (var s, i = 1, n = arguments.length; i < n; i++) {
  98024. s = arguments[i];
  98025. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  98026. t[p] = s[p];
  98027. }
  98028. return t;
  98029. };
  98030. var BABYLON;
  98031. (function (BABYLON) {
  98032. /**
  98033. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  98034. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  98035. * It also helps with the default setup of your imageProcessing configuration.
  98036. */
  98037. var EnvironmentHelper = /** @class */ (function () {
  98038. /**
  98039. * constructor
  98040. * @param options
  98041. * @param scene The scene to add the material to
  98042. */
  98043. function EnvironmentHelper(options, scene) {
  98044. var _this = this;
  98045. this._errorHandler = function (message, exception) {
  98046. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  98047. };
  98048. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  98049. this._scene = scene;
  98050. this.onErrorObservable = new BABYLON.Observable();
  98051. this._setupBackground();
  98052. this._setupImageProcessing();
  98053. }
  98054. /**
  98055. * Creates the default options for the helper.
  98056. */
  98057. EnvironmentHelper._getDefaultOptions = function () {
  98058. return {
  98059. createGround: true,
  98060. groundSize: 15,
  98061. groundTexture: this._groundTextureCDNUrl,
  98062. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98063. groundOpacity: 0.9,
  98064. enableGroundShadow: true,
  98065. groundShadowLevel: 0.5,
  98066. enableGroundMirror: false,
  98067. groundMirrorSizeRatio: 0.3,
  98068. groundMirrorBlurKernel: 64,
  98069. groundMirrorAmount: 1,
  98070. groundMirrorFresnelWeight: 1,
  98071. groundMirrorFallOffDistance: 0,
  98072. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  98073. groundYBias: 0.00001,
  98074. createSkybox: true,
  98075. skyboxSize: 20,
  98076. skyboxTexture: this._skyboxTextureCDNUrl,
  98077. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98078. backgroundYRotation: 0,
  98079. sizeAuto: true,
  98080. rootPosition: BABYLON.Vector3.Zero(),
  98081. setupImageProcessing: true,
  98082. environmentTexture: this._environmentTextureCDNUrl,
  98083. cameraExposure: 0.8,
  98084. cameraContrast: 1.2,
  98085. toneMappingEnabled: true,
  98086. };
  98087. };
  98088. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  98089. /**
  98090. * Gets the root mesh created by the helper.
  98091. */
  98092. get: function () {
  98093. return this._rootMesh;
  98094. },
  98095. enumerable: true,
  98096. configurable: true
  98097. });
  98098. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  98099. /**
  98100. * Gets the skybox created by the helper.
  98101. */
  98102. get: function () {
  98103. return this._skybox;
  98104. },
  98105. enumerable: true,
  98106. configurable: true
  98107. });
  98108. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  98109. /**
  98110. * Gets the skybox texture created by the helper.
  98111. */
  98112. get: function () {
  98113. return this._skyboxTexture;
  98114. },
  98115. enumerable: true,
  98116. configurable: true
  98117. });
  98118. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  98119. /**
  98120. * Gets the skybox material created by the helper.
  98121. */
  98122. get: function () {
  98123. return this._skyboxMaterial;
  98124. },
  98125. enumerable: true,
  98126. configurable: true
  98127. });
  98128. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  98129. /**
  98130. * Gets the ground mesh created by the helper.
  98131. */
  98132. get: function () {
  98133. return this._ground;
  98134. },
  98135. enumerable: true,
  98136. configurable: true
  98137. });
  98138. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  98139. /**
  98140. * Gets the ground texture created by the helper.
  98141. */
  98142. get: function () {
  98143. return this._groundTexture;
  98144. },
  98145. enumerable: true,
  98146. configurable: true
  98147. });
  98148. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  98149. /**
  98150. * Gets the ground mirror created by the helper.
  98151. */
  98152. get: function () {
  98153. return this._groundMirror;
  98154. },
  98155. enumerable: true,
  98156. configurable: true
  98157. });
  98158. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  98159. /**
  98160. * Gets the ground mirror render list to helps pushing the meshes
  98161. * you wish in the ground reflection.
  98162. */
  98163. get: function () {
  98164. if (this._groundMirror) {
  98165. return this._groundMirror.renderList;
  98166. }
  98167. return null;
  98168. },
  98169. enumerable: true,
  98170. configurable: true
  98171. });
  98172. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  98173. /**
  98174. * Gets the ground material created by the helper.
  98175. */
  98176. get: function () {
  98177. return this._groundMaterial;
  98178. },
  98179. enumerable: true,
  98180. configurable: true
  98181. });
  98182. /**
  98183. * Updates the background according to the new options
  98184. * @param options
  98185. */
  98186. EnvironmentHelper.prototype.updateOptions = function (options) {
  98187. var newOptions = __assign({}, this._options, options);
  98188. if (this._ground && !newOptions.createGround) {
  98189. this._ground.dispose();
  98190. this._ground = null;
  98191. }
  98192. if (this._groundMaterial && !newOptions.createGround) {
  98193. this._groundMaterial.dispose();
  98194. this._groundMaterial = null;
  98195. }
  98196. if (this._groundTexture) {
  98197. if (this._options.groundTexture != newOptions.groundTexture) {
  98198. this._groundTexture.dispose();
  98199. this._groundTexture = null;
  98200. }
  98201. }
  98202. if (this._skybox && !newOptions.createSkybox) {
  98203. this._skybox.dispose();
  98204. this._skybox = null;
  98205. }
  98206. if (this._skyboxMaterial && !newOptions.createSkybox) {
  98207. this._skyboxMaterial.dispose();
  98208. this._skyboxMaterial = null;
  98209. }
  98210. if (this._skyboxTexture) {
  98211. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  98212. this._skyboxTexture.dispose();
  98213. this._skyboxTexture = null;
  98214. }
  98215. }
  98216. if (this._groundMirror && !newOptions.enableGroundMirror) {
  98217. this._groundMirror.dispose();
  98218. this._groundMirror = null;
  98219. }
  98220. if (this._scene.environmentTexture) {
  98221. if (this._options.environmentTexture != newOptions.environmentTexture) {
  98222. this._scene.environmentTexture.dispose();
  98223. }
  98224. }
  98225. this._options = newOptions;
  98226. this._setupBackground();
  98227. this._setupImageProcessing();
  98228. };
  98229. /**
  98230. * Sets the primary color of all the available elements.
  98231. * @param color the main color to affect to the ground and the background
  98232. */
  98233. EnvironmentHelper.prototype.setMainColor = function (color) {
  98234. if (this.groundMaterial) {
  98235. this.groundMaterial.primaryColor = color;
  98236. }
  98237. if (this.skyboxMaterial) {
  98238. this.skyboxMaterial.primaryColor = color;
  98239. }
  98240. if (this.groundMirror) {
  98241. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  98242. }
  98243. };
  98244. /**
  98245. * Setup the image processing according to the specified options.
  98246. */
  98247. EnvironmentHelper.prototype._setupImageProcessing = function () {
  98248. if (this._options.setupImageProcessing) {
  98249. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  98250. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  98251. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  98252. this._setupEnvironmentTexture();
  98253. }
  98254. };
  98255. /**
  98256. * Setup the environment texture according to the specified options.
  98257. */
  98258. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  98259. if (this._scene.environmentTexture) {
  98260. return;
  98261. }
  98262. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  98263. this._scene.environmentTexture = this._options.environmentTexture;
  98264. return;
  98265. }
  98266. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  98267. this._scene.environmentTexture = environmentTexture;
  98268. };
  98269. /**
  98270. * Setup the background according to the specified options.
  98271. */
  98272. EnvironmentHelper.prototype._setupBackground = function () {
  98273. if (!this._rootMesh) {
  98274. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  98275. }
  98276. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  98277. var sceneSize = this._getSceneSize();
  98278. if (this._options.createGround) {
  98279. this._setupGround(sceneSize);
  98280. this._setupGroundMaterial();
  98281. this._setupGroundDiffuseTexture();
  98282. if (this._options.enableGroundMirror) {
  98283. this._setupGroundMirrorTexture(sceneSize);
  98284. }
  98285. this._setupMirrorInGroundMaterial();
  98286. }
  98287. if (this._options.createSkybox) {
  98288. this._setupSkybox(sceneSize);
  98289. this._setupSkyboxMaterial();
  98290. this._setupSkyboxReflectionTexture();
  98291. }
  98292. this._rootMesh.position.x = sceneSize.rootPosition.x;
  98293. this._rootMesh.position.z = sceneSize.rootPosition.z;
  98294. this._rootMesh.position.y = sceneSize.rootPosition.y;
  98295. };
  98296. /**
  98297. * Get the scene sizes according to the setup.
  98298. */
  98299. EnvironmentHelper.prototype._getSceneSize = function () {
  98300. var _this = this;
  98301. var groundSize = this._options.groundSize;
  98302. var skyboxSize = this._options.skyboxSize;
  98303. var rootPosition = this._options.rootPosition;
  98304. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  98305. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98306. }
  98307. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  98308. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  98309. });
  98310. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  98311. if (this._options.sizeAuto) {
  98312. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  98313. this._scene.activeCamera.upperRadiusLimit) {
  98314. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  98315. skyboxSize = groundSize;
  98316. }
  98317. var sceneDiagonalLenght = sceneDiagonal.length();
  98318. if (sceneDiagonalLenght > groundSize) {
  98319. groundSize = sceneDiagonalLenght * 2;
  98320. skyboxSize = groundSize;
  98321. }
  98322. // 10 % bigger.
  98323. groundSize *= 1.1;
  98324. skyboxSize *= 1.5;
  98325. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  98326. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  98327. }
  98328. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98329. };
  98330. /**
  98331. * Setup the ground according to the specified options.
  98332. */
  98333. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  98334. var _this = this;
  98335. if (!this._ground) {
  98336. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  98337. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  98338. this._ground.parent = this._rootMesh;
  98339. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  98340. }
  98341. this._ground.receiveShadows = this._options.enableGroundShadow;
  98342. };
  98343. /**
  98344. * Setup the ground material according to the specified options.
  98345. */
  98346. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  98347. if (!this._groundMaterial) {
  98348. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  98349. }
  98350. this._groundMaterial.alpha = this._options.groundOpacity;
  98351. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  98352. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  98353. this._groundMaterial.primaryColor = this._options.groundColor;
  98354. this._groundMaterial.useRGBColor = false;
  98355. this._groundMaterial.enableNoise = true;
  98356. if (this._ground) {
  98357. this._ground.material = this._groundMaterial;
  98358. }
  98359. };
  98360. /**
  98361. * Setup the ground diffuse texture according to the specified options.
  98362. */
  98363. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  98364. if (!this._groundMaterial) {
  98365. return;
  98366. }
  98367. if (this._groundTexture) {
  98368. return;
  98369. }
  98370. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  98371. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  98372. return;
  98373. }
  98374. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98375. diffuseTexture.gammaSpace = false;
  98376. diffuseTexture.hasAlpha = true;
  98377. this._groundMaterial.diffuseTexture = diffuseTexture;
  98378. };
  98379. /**
  98380. * Setup the ground mirror texture according to the specified options.
  98381. */
  98382. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  98383. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98384. if (!this._groundMirror) {
  98385. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  98386. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  98387. this._groundMirror.anisotropicFilteringLevel = 1;
  98388. this._groundMirror.wrapU = wrapping;
  98389. this._groundMirror.wrapV = wrapping;
  98390. this._groundMirror.gammaSpace = false;
  98391. if (this._groundMirror.renderList) {
  98392. for (var i = 0; i < this._scene.meshes.length; i++) {
  98393. var mesh = this._scene.meshes[i];
  98394. if (mesh !== this._ground &&
  98395. mesh !== this._skybox &&
  98396. mesh !== this._rootMesh) {
  98397. this._groundMirror.renderList.push(mesh);
  98398. }
  98399. }
  98400. }
  98401. }
  98402. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  98403. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  98404. };
  98405. /**
  98406. * Setup the ground to receive the mirror texture.
  98407. */
  98408. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  98409. if (this._groundMaterial) {
  98410. this._groundMaterial.reflectionTexture = this._groundMirror;
  98411. this._groundMaterial.reflectionFresnel = true;
  98412. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  98413. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  98414. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  98415. }
  98416. };
  98417. /**
  98418. * Setup the skybox according to the specified options.
  98419. */
  98420. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  98421. var _this = this;
  98422. if (!this._skybox) {
  98423. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  98424. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  98425. }
  98426. this._skybox.parent = this._rootMesh;
  98427. };
  98428. /**
  98429. * Setup the skybox material according to the specified options.
  98430. */
  98431. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  98432. if (!this._skybox) {
  98433. return;
  98434. }
  98435. if (!this._skyboxMaterial) {
  98436. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  98437. }
  98438. this._skyboxMaterial.useRGBColor = false;
  98439. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  98440. this._skyboxMaterial.enableNoise = true;
  98441. this._skybox.material = this._skyboxMaterial;
  98442. };
  98443. /**
  98444. * Setup the skybox reflection texture according to the specified options.
  98445. */
  98446. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  98447. if (!this._skyboxMaterial) {
  98448. return;
  98449. }
  98450. if (this._skyboxTexture) {
  98451. return;
  98452. }
  98453. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  98454. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  98455. return;
  98456. }
  98457. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  98458. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  98459. this._skyboxTexture.gammaSpace = false;
  98460. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  98461. };
  98462. /**
  98463. * Dispose all the elements created by the Helper.
  98464. */
  98465. EnvironmentHelper.prototype.dispose = function () {
  98466. if (this._groundMaterial) {
  98467. this._groundMaterial.dispose(true, true);
  98468. }
  98469. if (this._skyboxMaterial) {
  98470. this._skyboxMaterial.dispose(true, true);
  98471. }
  98472. this._rootMesh.dispose(false);
  98473. };
  98474. /**
  98475. * Default ground texture URL.
  98476. */
  98477. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  98478. /**
  98479. * Default skybox texture URL.
  98480. */
  98481. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  98482. /**
  98483. * Default environment texture URL.
  98484. */
  98485. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  98486. return EnvironmentHelper;
  98487. }());
  98488. BABYLON.EnvironmentHelper = EnvironmentHelper;
  98489. })(BABYLON || (BABYLON = {}));
  98490. //# sourceMappingURL=babylon.environmentHelper.js.map
  98491. var BABYLON;
  98492. (function (BABYLON) {
  98493. /**
  98494. * This class is made for on one-liner static method to help creating particle systems.
  98495. */
  98496. var ParticleHelper = /** @class */ (function () {
  98497. function ParticleHelper() {
  98498. }
  98499. /**
  98500. * This is the main static method (one-liner) of this helper to create different particle systems.
  98501. * @param type This string represents the type to the particle system to create
  98502. * @param emitter The object where the particle system will start to emit from.
  98503. * @param scene The scene where the particle system should live.
  98504. * @param gpu If the system will use gpu.
  98505. * @returns the ParticleSystem created.
  98506. */
  98507. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  98508. var _this = this;
  98509. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  98510. if (gpu === void 0) { gpu = false; }
  98511. return new Promise(function (resolve, reject) {
  98512. if (scene) {
  98513. _this._scene = scene;
  98514. }
  98515. else {
  98516. return reject("A particle system need a scene.");
  98517. }
  98518. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  98519. return reject("Particle system with GPU is not supported.");
  98520. }
  98521. _this._emitter = emitter;
  98522. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  98523. var newData = JSON.parse(data.toString());
  98524. return resolve(_this._createSystem(newData));
  98525. }, undefined, undefined, undefined, function (req, exception) {
  98526. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  98527. });
  98528. });
  98529. };
  98530. ParticleHelper._createSystem = function (data) {
  98531. // Create a particle system
  98532. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  98533. // Texture of each particle
  98534. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  98535. // Where the particles come from
  98536. system.emitter = this._emitter; // the starting object, the emitter
  98537. // Colors of all particles
  98538. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  98539. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  98540. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  98541. // Size of each particle (random between...
  98542. system.minSize = data.minSize;
  98543. system.maxSize = data.maxSize;
  98544. // Life time of each particle (random between...
  98545. system.minLifeTime = data.minLifeTime;
  98546. system.maxLifeTime = data.maxLifeTime;
  98547. // Emission rate
  98548. system.emitRate = data.emitRate;
  98549. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  98550. system.blendMode = data.blendMode;
  98551. // Set the gravity of all particles
  98552. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  98553. // Angular speed, in radians
  98554. system.minAngularSpeed = data.minAngularSpeed;
  98555. system.maxAngularSpeed = data.maxAngularSpeed;
  98556. // Speed
  98557. system.minEmitPower = data.minEmitPower;
  98558. system.maxEmitPower = data.maxEmitPower;
  98559. system.updateSpeed = data.updateSpeed;
  98560. switch (data.emitterType) {
  98561. case "box":
  98562. if (!data.direction1 || !data.direction2) {
  98563. throw new Error("Directions are missing in this particle system.");
  98564. }
  98565. if (!data.minEmitBox || !data.maxEmitBox) {
  98566. throw new Error("EmitBox is missing in this particle system.");
  98567. }
  98568. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  98569. break;
  98570. case "sphere":
  98571. system.createSphereEmitter(data.radius);
  98572. break;
  98573. case "directed_sphere":
  98574. if (!data.direction1 || !data.direction2) {
  98575. throw new Error("Directions are missing in this particle system.");
  98576. }
  98577. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  98578. break;
  98579. case "cone":
  98580. system.createConeEmitter(data.radius, data.angle);
  98581. break;
  98582. default:
  98583. break;
  98584. }
  98585. return system;
  98586. };
  98587. /**
  98588. * Base Assets URL.
  98589. */
  98590. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  98591. return ParticleHelper;
  98592. }());
  98593. BABYLON.ParticleHelper = ParticleHelper;
  98594. })(BABYLON || (BABYLON = {}));
  98595. //# sourceMappingURL=babylon.particleHelper.js.map
  98596. var BABYLON;
  98597. (function (BABYLON) {
  98598. /**
  98599. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  98600. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  98601. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  98602. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  98603. */
  98604. var VideoDome = /** @class */ (function (_super) {
  98605. __extends(VideoDome, _super);
  98606. /**
  98607. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  98608. * @param name Element's name, child elements will append suffixes for their own names.
  98609. * @param urlsOrVideo
  98610. * @param options An object containing optional or exposed sub element properties:
  98611. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  98612. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  98613. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  98614. * @param options **loop=true** Automatically loop video on end.
  98615. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  98616. */
  98617. function VideoDome(name, urlsOrVideo, options, scene) {
  98618. var _this = _super.call(this, name, scene) || this;
  98619. // set defaults and manage values
  98620. name = name || "videoDome";
  98621. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  98622. options.clickToPlay = Boolean(options.clickToPlay);
  98623. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  98624. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  98625. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  98626. // create
  98627. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  98628. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  98629. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  98630. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  98631. flat: false,
  98632. radius: options.size,
  98633. subdivisions: options.resolution,
  98634. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  98635. }, scene);
  98636. // configure material
  98637. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  98638. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  98639. material.reflectionTexture = _this._videoTexture;
  98640. material.useEquirectangularFOV = true;
  98641. material.fovMultiplier = 1.0;
  98642. // configure mesh
  98643. _this._mesh.material = material;
  98644. _this._mesh.parent = _this;
  98645. // optional configuration
  98646. if (options.clickToPlay) {
  98647. scene.onPointerUp = function () {
  98648. _this._videoTexture.video.play();
  98649. };
  98650. }
  98651. return _this;
  98652. }
  98653. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  98654. /**
  98655. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98656. * Also see the options.resolution property.
  98657. */
  98658. get: function () {
  98659. return this._material.fovMultiplier;
  98660. },
  98661. set: function (value) {
  98662. this._material.fovMultiplier = value;
  98663. },
  98664. enumerable: true,
  98665. configurable: true
  98666. });
  98667. /**
  98668. * Releases resources associated with this node.
  98669. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  98670. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  98671. */
  98672. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  98673. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  98674. this._videoTexture.dispose();
  98675. this._mesh.dispose();
  98676. this._material.dispose();
  98677. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  98678. };
  98679. return VideoDome;
  98680. }(BABYLON.Node));
  98681. BABYLON.VideoDome = VideoDome;
  98682. })(BABYLON || (BABYLON = {}));
  98683. //# sourceMappingURL=babylon.videoDome.js.map
  98684. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\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(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=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; \nvec2 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\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); \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;\nin vec2 angle;\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);\nvec2 cornerPos=offset*size;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n\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;\nuniform vec2 angleRange;\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 coneAngle;\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;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\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;\noutAngle=angle;\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\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\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 (coneAngle == 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;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\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"};
  98685. 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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  98686. globalObject["BABYLON"] = BABYLON;
  98687. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var serializeAsCameraReference = BABYLON.serializeAsCameraReference;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var RawTexture3D = BABYLON.RawTexture3D;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var UtilityLayerRenderer = BABYLON.UtilityLayerRenderer;var Gizmo = BABYLON.Gizmo;var AxisDragGizmo = BABYLON.AxisDragGizmo;var PositionGizmo = BABYLON.PositionGizmo;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var PointerDragBehavior = BABYLON.PointerDragBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var ParticleHelper = BABYLON.ParticleHelper;var VideoDome = BABYLON.VideoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var Debug = BABYLON.Debug ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  98688. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,serializeAsCameraReference,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,RayHelper,DebugLayer,BoundingBoxRenderer,UtilityLayerRenderer,Gizmo,AxisDragGizmo,PositionGizmo,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,PointerDragBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,ParticleHelper,VideoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,Debug ,JoystickAxis ,SimplificationType ,AssetTaskState };